我有一個存盤 (x, y) 值的 Point 串列。清單是這個
List<Point> path = new ArrayList<>();
但是,我希望能夠從該串列中獲取特定索引的先前索引。例如我有這個點串列:
[(4,4), (1,4), (2,3), (0,1)]
如何獲得 (2,3) 的先前索引,即 (1,4),(4,4)?有什么幫助嗎?
uj5u.com熱心網友回復:
您需要覆寫該equals(Object obj)方法,以便我們可以執行搜索。
class Point {
public int x, y;
public Point(int x, int y){ this.x=x; this.y=y;}
public boolean equals(Object o){
if (o instanceof Point){
Point p = (Point) o;
return x == p.x && y == p.y;
}
return false;
}
public String toString(){
return String.format("(%d,%d)", x,y);
}
}
indexOf()將回傳找到 p 的索引。或者你可以List.indexOf()改用。
static int indexOf(List<Point> path, Point p){
for(int i=0; i<path.size(); i )
if (path.get(i).equals(p)) return i;
return -1;
}
找到該點的索引 該點之前的每個點都是之前的點。
public static void main(String[] args) {
List<Point> path = new ArrayList<>(
List.of(new Point(0,0), new Point(1,1),
new Point(2,2), new Point(3,3)));
int index = indexOf(path, new Point(2,2));
List<Point> prevs = new ArrayList<>();
for(int i=0; i<index; i )
prevs.add(path.get(i));
System.out.println(prevs);
}
輸出:
[(0,0), (1,1)]
uj5u.com熱心網友回復:
你可以這樣做:
// Define the point or get the point that you are searching for some different way
Point x = Point(2,3)
int previousIndex = path.indexOf(x) - 1;
// Make sure we are not out of bounds
if (previousIndex >= 0){
return path.get(previousIndex)
// Would return (1, 4)
}
利用indexOf并確保您沒有越界。這就是它的全部內容。如果你想獲得所有以前的積分,你可以做這樣的事情
new ArrayList(paths.subList(0 ,previousIndex 1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384852.html
