0

When I use Iterator it = denseBagMap.keySet().iterator(), this would only return a key once even though if it contains more than once. But I want to be able to return an element let's say if 'a' occurs 3 times. The next method should be able to return "a" three times but I am not sure how can I do that. I am sort of slow in this but it would be helpful if someone can hopefully show me the iterator with an actual code. Only hasNext() and next() method are required for an iterator.

public class DenseBag<T> extends AbstractCollection<T> {

private Map<T, Integer> denseBagMap;
private int size;  // Total number of elements in the bag
/**
 * Initialize a new, empty DenseBag
 */
public DenseBag() {
    denseBagMap = new HashMap<T, Integer>();

};
    public boolean equals(Object o) {
    if (o == this) {
        return true;
    }
    if (!(o instanceof DenseBag)) {
        return false;
    }
    DenseBag<T> dense = (DenseBag<T>) o;
    return size == dense.size;

}
    public int hashCode() {
    return this.denseBagMap.hashCode();

}
    //I am not sure how to write an iterator method for this.
    public Iterator<T> iterator() {
    return new Iterator<T>() {

  public boolean hasNext(){
 }

  public T next(){
 }
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
ivesingh
  • 888
  • 3
  • 12
  • 30

2 Answers2

0

A keySet is, by definition, a Set and therefore contains only one entry for each key. If you wish to store all entries added under each key you should use something like the Apache MultiMap.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

put there return new denseBagMap.keySet().iterator();

Miloš Lukačka
  • 842
  • 1
  • 11
  • 25