[英]Java: Search in ArrayList an element from object
Let's say I have this: 假设我有这个:
// Create arrayList
ArrayList<Point> pointList = new ArrayList<Point>();
// Adding some objects
pointList.add(new Point(1, 1);
pointList.add(new Point(1, 2);
pointList.add(new Point(3, 4);
How can I get the index position of an object by searching one of its parameters? 如何通过搜索其中一个参数来获取对象的索引位置?
I tried this but doesn't work.
我尝试了这个但是没有用。
pointList.indexOf(this.x(1));
Thanks in advance. 提前致谢。
You have to loop through the list yourself: 你必须自己遍历列表:
int index = -1;
for (int i = 0; i < pointList.size(); i++)
if (pointList.get(i).x == 1) {
index = i;
break;
}
// now index is the location of the first element with x-val 1
// or -1 if no such element exists
You need to create a custom loop to do that. 您需要创建一个自定义循环来执行此操作。
public int getPointIndex(int xVal) {
for(int i = 0; i < pointList.size(); i++) {
if(pointList.get(i).x == xVal) return i;
}
return -1; //Or throw error if it wasn't found.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.