1

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.

1
  • Didn't know how to explain. Forget it. =) Commented Dec 31, 2012 at 20:08

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, it worked as expected. Why I didn't think that before? Your answer was first of all. Marked as correct.
1

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

4 Comments

null is not a valid return type for int.
Whoops, fixed. There's two hours of sleep for you.
Thanks for your answer. Same as A. R. S. but in a method. It worked.
No problem! Didn't mean to post a duplicate, but got ninja'd :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.