简体   繁体   中英

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM