我在尝试将公共(public)迭代器放入类中以读取类中的 Map 并在其他类中实现此迭代器时遇到问题。或者换句话说,
我有 A 类。A 类包含一个私有(private) HashMap,我想通过迭代此映射的公共(public)迭代器访问它。
我也有 B 类。我试图在 B 类中运行这个迭代器来读取 A 类的内容。
这可能看起来有点迂回(或者更确切地说,很多迂回),但我的作业指定类 A 中的数据系统对其他类隐藏,并建议使用公共(public)迭代器访问数据。有一个示例说明 B 类中的方法可能是什么样子,我已尽我所能遵循该示例。
虽然无法让它工作。
这是我的代码模型。我尝试编译它,它与我的真实代码完全一样。
// this is class A
public class Giant {
private Map<Item, Integer> myMap = new HashMap<Item, Integer>();
// add a bunch of items to the map, check if they worked fine
public Iterator<Map.Entry<Item, Integer>> giantIterator = myMap.entrySet().iterator();
}
// and this is in class B
public void receive(Giant mouse){
System.out.println("I've started!");
Iterator<Map.Entry<Item, Integer>> foo = mouse.giantIterator;
while (foo.hasNext()) {
Map.Entry<Item, Integer> entry = foo.next();
System.out.println("I'm working!");
}
}
我还有一个测试类,它创建任一类的对象,然后运行 receive
方法。
我收到消息“我已经开始了!”但不是“我在工作!”
同时,如果我让任一类中的两个迭代器打印一个 toString
,则 toString 是相同的。
我也不能简单地将我应该在 B 类中执行的操作移到 A 类中,因为迭代器在几个不同的方法中,并且在每个方法中用于略有不同的事情。
我有点难过。我在语法中遗漏了什么吗?我进口错了吗?我是否完全搞砸了这应该如何工作?这完全不可能吗?
最佳答案
尝试通过这样的函数公开迭代器:
public class Giant {
private Map<Item, Integer> myMap = new HashMap<Item, Integer>();
public Iterator<Map.Entry<Item, Integer>> getGiantIterator() {
return myMap.entrySet().iterator();
}
}
在 B 类中更改:
Iterator<Map.Entry<Item, Integer>> foo = mouse.giantIterator;
到
Iterator<Map.Entry<Item, Integer>> foo = mouse.getGiantIterator();
这样迭代器直到需要时才会被创建。
按照您的编码方式,迭代器是在 map 仍为空时创建的。我怀疑这可能是您问题的根源。
关于Java:在其他类中使用迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15129015/