Databricks | Phone | Custom Hashset

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2022-03-01Added By Anonymous
Source: Link

Create a 'custom set' class that has the methods like add(),remove(),contains(),iterator() like a regular set, but we should be able to modify the set while it is being iterated. And the iterator should only contain the elements when it was called.


1class CustomSet { 2 3 public boolean add(int i){ 4 } 5 6 public boolean remove(int i){ 7 } 8 9 public boolean contains(int i){ 10 } 11 12 public Iterator<Integer> iterator(){ 13 } 14 15 public void printAll(){ 16 //print all elements using the iterator 17 } 18}


For example calls to the custom set should behave as follows:

1CustomSet set = new CustomSet(); 2set.add(1); //return true 3set.add(2); //return true 4set.add(3); //return true 5set.add(4); //return true 6Iterator<Integer> itr1 = set.iterator(); //itrerator should have 1,2,3,4 7set.remove(1); //return true; 8set.printAll(); //should print 1,2,3,4, because the set had 1,2,3,4 when the iterator was initialized. 9set.contains(1); //return false; because 1 was removed. 10Iterator<Integer> itr2 = set.iterator(); //itrerator should have 2,3,4 11set.printAll(); //should print 2,3,4, because the set had 2,3,4 when the iterator was initialized.
Comments