[英]Java: Search in ArrayList an element from object
假設我有這個:
// 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);
如何通過搜索其中一個參數來獲取對象的索引位置?
我嘗試了這個但是沒有用。
pointList.indexOf(this.x(1));
提前致謝。
你必須自己遍歷列表:
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
您需要創建一個自定義循環來執行此操作。
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.