indexOf() will not find a custom object type

ajay picture ajay · Jul 25, 2014 · Viewed 14.9k times · Source

The following code does not give me right answer.

class Point {

    int x; int y;
    public Point(int a,int b){
        this.x=a;this.y=b;
    }
}

class A{

    public static void main(String[] args){

        ArrayList<Point> p=new ArrayList<Point>();
        p.add(new Point(3,4));
        p.add(new Point(1,2));
        System.out.println(p.indexOf(1,2));

    }
}

This gives -1;

In general if arraylist of point is given, how can we find index of a particular point in in array ?

Answer

ali haider picture ali haider · Jul 25, 2014

indexOf requires the object as input. If it does not find the object you are passing in, it will return -1. You need to pass the object whose location in the arraylist you are looking for as the input into the indexOf function. You should also override hashcode and equals for your class in this case.

Override hashcode and equals in your class Point. Then once you create instances of this class Point (using the new keyword) and add them to the arrayList, you can use the indexOf call on the arrayList using any of the Point objects as a parameter to the indexOf call.

Class Point

public class Point {

        int x; 
        int y;

        public Point(int a, int b) {
        this.x=a;this.y=b;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + x;
            result = prime * result + y;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Point other = (Point) obj;
            if (x != other.x)
                return false;
            if (y != other.y)
                return false;
            return true;
        }       
}

Class Test (you called it "a"):

import java.util.ArrayList;

public class Test {

     public static void main(String[] args){

            ArrayList<Point> p=new ArrayList<Point>();

            Point p1 = new Point(3,4);
            Point p2 = new Point(1,2);

            p.add(new Point(3,4));
            p.add(new Point(1,2));

            System.out.println(p.indexOf(p1));
     }

}