2

I have a java LinkedList which contains several custom objects of the same type.

LinkedList<myClass> = new LinkedList<myClass>();

Within my objects I have a specific value

class myClass(){
    public int id;
}

I want to be able to return the index of the linked list for a match of a specific value, i.e: Find the LinkedList index where the object id = 7

I have looked into using indexof, contains, and containsall, but without any luck (index of always returns -1).

Is this something I can do with a prebuild libary, or am I going to have to extend my own search function for custom objects?

MikO
  • 16,652
  • 11
  • 69
  • 103
James Winters
  • 59
  • 1
  • 4
  • you need your own search function – Aleksei Bulgak Apr 21 '13 at 15:44
  • In a real world scenario linked lists are never associated with index numbers. So in case u need to find the index you have to traverse your whole list. Otherwise what would be the difference between a linked list and an array that has indices. A linked list is dynamic. SO either u keep track of indices dynamically or you use the method I mentioned in the beginning. – Sohaib Apr 21 '13 at 15:44
  • Thanks for the replies. I built my own search function which was a lot quicker to do than I expected! For large data sets I would consider the accepted answer. Cheers! – James Winters Apr 21 '13 at 16:10

5 Answers5

1

Override the equals method on your myClass class so the LinkedList could find the object:

public class myClass {
    private int id; //it should be private, not public
    //other attributes...
    //getters and setters...

    @Override
    public void equals(Object o) {
        if (o == null) return false;
        if (o == this) return true;
        if (o instanceof myClass) {
            myClass x = (myClass)x;
            return x.getId() == this.id;
        }
        return false;
    }
}

Since you're overriding equals, you should also override the hashCode method:

@Override
public int hashCode() {
    return this.id;
}

The reason for this is explained in the Object class javadoc:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
0

This can be implemented in terms of List's indexOf() method, all you have to do is override equals() and hashChode() in myClass to specify that the comparisons must be made using the id attribute (here is an explanation of why you need to override both methods). Simply add this methods to myClass:

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

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

Now to find the index of an element with id == 7 do something like this:

int idx = myList.indexOf(new myClass(7));

That is, assuming that there exists a constructor in myClass that takes the id as a parameter.

Community
  • 1
  • 1
Óscar López
  • 215,818
  • 33
  • 288
  • 367
0

Maybe you shoud simple store your objects in an HashMap<key,value>
you put an object in it as value with a key. If you want to search for an Object you just get it over the key. So for example you take your class and use the objectID as key if its unique.

HashMap<Integer, myClass> list = new HashMap<Integer, myClass>();
list.put(newId, new MyClass(newId)); //just an example!

to find it now you just need one line like this:

list.get(newId);

if the newId does not exsist it return null.

BennX
  • 6,096
  • 3
  • 34
  • 81
  • Thanks for the replies. I built my own search function which was a lot quicker to do than I expected! For large data sets I would consider the accepted answer. Cheers! – James Winters Apr 21 '13 at 16:11
0

LinkedList compares Object using their equals() method. So if you want two instances of your class to be considered equal when they have the same ID, you must override the equals() method:

@Override
public boolean equals(Object o) {
    if (o == this) {
        return true;
    }
    if (o == null) {
        return false;
    }
    if (o.getClass() == this.getClass()) {
        return this.id == ((MyClass) o).id;
    }
    return false;
}

When overriding equals(), hashCode() must also be overridden, because two equals objects MUST have the same hashCode:

@Override
public int hashCode() {
    return id;
}

Note that if you don't want two instances to be considered equal when they have the same ID, then you have no choice other than iterating the list and finding the first element which has the same ID as the instance you're looking for. Or you must use another data structure, like a Map<Integer, MyClass> for example.

JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
0

You can do it like this

    list.indexOf(new Object() {
        @Override
        public boolean equals(Object o) {
            MyClass mine = (MyClass) o;
            return mine.id == yourValue;
        }
    });
Omar Sebres
  • 146
  • 1
  • 9