繁体   English   中英

我如何使用java中的list Structures确定java中当前元素之后是否存在其他元素

[英]How I can determine if there is another element after the current one or not in java using list Structures in java

我正在尝试编写一个名为boolean hasNext()的函数,它检查当前的元素之后是否还有另一个元素我是否有一个名为TourElement的类,它包含很多点。 这是我的代码// class waypoint:

public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

// class tourElement

 public class TourElement {
     private Waypoint points;
     private TourElement next;

      public void setWaypoint( Waypoint points){
       this.points = points; 
     }
      public void setTourElement(TourElement next) {
          this.next = next;
      }
     Waypoint getWaypoint() {
         return this.points;
     }

     TourElement getNext(){
         return this.next;
     }

    boolean hasNext(Waypoint first){
    // What am I doing wrong here?
        TourElement current = getNext();
        while( current.next != null)
        {
            return true;
        }
        return false;

    }
    // my test case
         public void testHasNext()
        {
           TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});

            assertEquals(true,elem.hasNext(createWaypoint(1, 1)));
        }

//创建元素列表:

private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

//创建航点:

private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

我期望用我的hasNext函数,如果我传递像{1,1}这样的点,它将返回true,因为在这一点之后还有一点。 但是当我通过{2,2}时。 它将返回false

你的方法可以改进。 看一看

boolean hasNext(){
    if (this.next != null) return true;
    return false;
}

您不需要循环到LinkledList的末尾,您应该只关心接下来的内容。

这一行:

assertEquals(true,elem.hasNext(createWaypoint(1, 1)));

将始终使断言失败,因为您正在创建新的航点,然后尝试在现有航点列表中找到它。 但是这个新的航路点不在列表中

列表中唯一的航点是您添加的航点,这是一个全新的航点,恰好具有与列表中某个航点相同的x和y值。

你没有包含TourElement.addStart方法的代码,所以我不知道那里是否有任何问题。 其他人指出你不需要在hasNext里面循环。 但这里的主要问题是除了使用传入hasNext方法的WayPoint之外,还需要做一些事情。 这可能会涉及遍历航点图试图找到一个现有的WayPoint有相同的x和y值作为一个传递到方法,然后检查是否一个next

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM