簡體   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