当我使用Iterator it = denseBagMap.keySet()。iterator()时,即使它包含多次,它也只会返回一次密钥。但是我希望能够返回一个元素让我们假设'a'发生3次。下一个方法应该能够返回“a”三次,但我不知道该怎么做。我在这方面有点慢,但如果有人能够用实际代码向我展示迭代器,这将会有所帮助。迭代器只需要hasNext()和next()方法。如何编写HashMap迭代器?
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(){
}
猜你应该检索'denseBagMap.entrySet()。iterator()'。 – 2013-04-05 23:13:21
您可能会发现重用或研究Guava的['HashMultiset'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common /collect/HashMultiset.html)。 – 2013-04-05 23:20:57
另一个dupe http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap – 2013-04-05 23:27:01