I need to write an iterator class that goes over the objects in a collection. Th
ID: 3624045 • Letter: I
Question
I need to write an iterator class that goes over the objects in a collection. The collection class will contain in instance variable of type Map<T, Integer> and an integer instance variable that represents the number of elements in the collection.
For example, if T happens to represent type "String", then we can imagine a DenseBag(the collection) containing the following:
"apple", "apple", "apple", "duck", "duck", "zebra", "zebra", "zebra", "zebra"
In this case the underlying map would look like this:
KEY VALUE
================
"apple" 3
"duck" 2
"zebra" 4
The iterator for a dense bag must iterate over all instances, including duplicates. In other words, if a bag contains 5 instances of the String "a", an iterator will generate the String "a" 5 times.
I really have no idea how to go about writing my own iterator class for this collection. Note: The iterator class will not support the remove method so I don't need to worry about that.
Any thoughts on how to do this would be greatly appreciated. Thank you.
Explanation / Answer
Dear, Declaring a string object importing the following classes import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; String[] fruits={"apple", "apple", "apple", "duck", "duck", "zebra", "zebra", "zebra", "zebra"};List<String> list=new ArrayList<String >(); Collections<String> col=list.Collections(); Collections.sort(list); Iterator<String> iterator=col.iterator(); To remove duplicates from array list HashSet<String> hashSet = new HashSet<String>(list); ArrayList<String > list2=new ArrayList<String >(hashSet);
Hope this will help you ArrayList<String > list2=new ArrayList<String >(hashSet);