从点列表中获取索引的前一个元素
Posted
技术标签:
【中文标题】从点列表中获取索引的前一个元素【英文标题】:Get the previous element of an index from a Point list 【发布时间】:2022-01-20 18:25:38 【问题描述】:我有一个存储 (x, y) 值的点列表。名单是这样的
List<Point> path = new ArrayList<>();
但是,我希望能够从该列表中获取特定索引的前一个索引。例如我有这个点列表:
[(4,4), (1,4), (2,3), (0,1)]
如何获得 (2,3) 的前一个索引,即 (1,4),(4,4)? 有什么帮助吗?
【问题讨论】:
“上一个索引”是什么意思? of (2,3) 前一个将是 (1,4)。 那么(4,4)
呢?
确定为什么不 :)
对于你拥有的那个列表,path.get(0)
会得到你(4,4)
和path.get(1)
会得到你(1,4)
。因此,如果您知道当前点是什么索引,那么 index-1
将为您提供前一个索引。这是你想要的吗?
【参考方案1】:
您需要重写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)]
【讨论】:
【参考方案2】:你可以这样做:
// 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))
【讨论】:
以上是关于从点列表中获取索引的前一个元素的主要内容,如果未能解决你的问题,请参考以下文章