【问题标题】:Using iterator object to loop throuh arraylist and check if it is higher than a value使用迭代器对象循环遍历arraylist并检查它是否高于某个值
【发布时间】:2018-05-05 00:58:42
【问题描述】:

我有一个静态方法,我需要完成它。

我要做的是使用迭代器来检查 y 坐标是否大于最大值并返回该值。这就是我现在所拥有的。

import java.awt.*;

public static Point highestPoint(List<Point> points) {
Iterator<Point> pointIterator = points.iterator();
int highest = 0;
Point highestPoint = null;
while (pointIterator.hasNext()) {
   pointIterator.next()
    if (points.getY() > highest) {
      highest = points.get(Y);
  }

}


return highestPoint;
}

当我运行我的代码时,我收到一个语法错误:

Main.java:12: error: cannot find symbol
  if (points.getY() > highest) {
            ^
symbol:   method getY()
location: variable points of type List<Point>
Main.java:13: error: cannot find symbol
      highest = points.getY();
                      ^
symbol:   method getY()
location: variable points of type List<Point>
2 errors

【问题讨论】:

  • 我会使用points.stream().mapToInt(Point::getY).max().orElse(IllegalArgumentException::new)
  • 还没有人反对这个? 1. 您不能在列表 2 上使用 getY()。为什么需要使用迭代器,任何特定的用例?使用流最大功能
  • @Deepak If you think thats bad..。所以偏离了它的高质量问答库的标准。它已经转向“解决他们的问题。他们不再有这个问题,你就会获得代表。代表会吸引你的个人资料。”我曾经是about quality (example )。现在看看我。
  • @Vince,一开始我只是在讽刺和搞笑。无意冒犯,但我问的是一个简单的问题,为什么需要迭代器。如果除了查找 max 之外不需要创建额外的 interator 对象,则使用 stream
  • 你显然不知道downvote按钮的用途,@Deepak

标签: java iterator


【解决方案1】:

将next() 的结果存储在一个变量中

Point currentPoint = pointIterator.next();

检查当前的highestPoint 是否为null。如果是这样,请将currentPoint 设置为最高:

if(highestPoint == null)
    highestPoint = currentPoint;

否则,将最高点与当前比较:

if(highestPoint == null)
    highestPoint = currentPoint;
else if(highestPoint.getY() < currentPoint.getY())
    highestPoint = currentPoint;

不需要int highest。您的最终结果将是:

public Point highestPoint(List<Point> points) {
    Point highestPoint = null;

    Iterator<Point> pointIterator = points.iterator();
    while(pointIterator.hasNext()) {
        Point currentPoint = pointIterator.next();

        if(highestPoint == null || highestPoint.getY() < currentPoint.getY())
            highestPoint = currentPoint;
    }

    return highestPoint;
}

【讨论】:

    【解决方案2】:

    points 是一个列表,因此您不能在其上调用 getY()。您需要先通过调用 pointIterator.next() 获取 Point 对象,然后对其调用 getY() 方法。

    while (pointIterator.hasNext()) {
        Point point = pointIterator.next();
        if (point.getY() > highest) {
            highest = point.get(Y);
         }
    }
    

    您也可以使用流和删除整个样板代码来实现相同的目的

    Point highest = points.stream().max((p1, p2) -> p1.getY() > p2.getY() ? 1 : -1).get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      相关资源
      最近更新 更多