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.

Upvotes: 1

Views: 8869

Answers (2)

user1131435
user1131435

Reputation:

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

Upvotes: 1

arshajii
arshajii

Reputation: 129507

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

Upvotes: 3

Related Questions