【问题标题】:How to write HashMap iterator?如何编写HashMap迭代器?
【发布时间】:2013-04-05 23:12:05
【问题描述】:

当我使用 Iterator it = denseBagMap.keySet().iterator() 时,即使它包含多次,它也只会返回一个键。但我希望能够返回一个元素,假设“a”出现 3 次。下一个方法应该能够返回“a”三次,但我不确定我该怎么做。我在这方面有点慢,但如果有人可以向我展示带有实际代码的迭代器,那将会很有帮助。迭代器只需要 hasNext() 和 next() 方法。

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(){
 }

【问题讨论】:

标签: java iterator hashmap


【解决方案1】:

根据定义,keySetSet,因此每个键只包含一个条目。如果您希望存储在每个键下添加的所有条目,您应该使用 Apache MultiMap 之类的东西。

【讨论】:

    【解决方案2】:

    放在那里 return new denseBagMap.keySet().iterator();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2015-02-20
      相关资源
      最近更新 更多