[英]Java Method is Undefined for Type Iterator
我有一个Ball类和一个BallContainer类。 该BallContainer类包含球对象,叫的LinkedHashSet contents
。 我正在编写的一种方法称为differentColors()
,顾名思义,该方法返回集合中球的不同颜色数的整数值。
下面是该方法的代码片段:
int count = 0;
for(Iterator<Ball> b = contents.iterator(); b.hasNext();) {
if(b.getColor().equals(b.next().getColor())){
count++;
}
}
我试图通过Ball迭代器在列表中循环,并且Eclipse IDE给我一个错误,指出getColor() method is undefined for type Iterator<Ball>
的getColor() method is undefined for type Iterator<Ball>
。 对我来说,这没有任何意义。 b是Ball类类型的迭代器,因此它能够访问Ball对象方法。 我查阅了有关使用Java迭代器的文档,发现在尝试打印列表或集合中的“当前”元素时,将使用.next()方法,因为迭代器位于当前元素的“后面”,因此说话。
所以我尝试将代码修改为b.next().getColor().equals(b.next().next().getColor())
,以便访问“当前”元素的颜色并将其与NEXT元素的颜色进行比较颜色。 Eclipse大叫我,因为the next() method is undefined for type Ball
。 有人可以向我解释发生了什么事以及如何纠正此问题吗? 谢谢
使用“最后一种颜色”变量并一次查看一种颜色会更好。 另外,如果您确实要检测颜色变化,则需要取消相等性测试。 如果该集合是按颜色排序的,则可以使用以下内容:
int count = 0;
Color lastColor = null;
for (Ball ball : contents) {
Color nextColor = ball.getColor();
if (!nextColor.equals(lastColor)) {
count++;
lastColor = nextColor;
}
}
如果以其他方式排序,则需要其他逻辑。 我建议您保留Set<Color>
:
int count = 0;
Set<Color> seenColors = new HashSet<>();
for (Ball ball : contents) {
if (seenColors.add(ball.getColor())) {
count++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.