Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override indexOf in LinkedList to check for identity, not equality

Tags:

java

list

indexof

I have a List (actually a LinkedList) and I add Items to it which implement the equals-method.

The problem is that I add items that are equal, but not identical (like two initialized objects). Now, when I want to get the index of the item I added second, I get, of course, the element of the first item, because indexOf searches for equality and not identity.

I tried to create my own subclass of LinkedList and overwrite the indexOf-method, but this is not possible, because I don't have access to neither the subclass Node nor the Node-Element first.

Here is an example:

public class ExampleObject {

  int number;

  public ExampleObject(){
    number = 0;
  }

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

  public static void main(String[] args) {
    LinkedList<ExampleObject> list = new LinkedList<ExampleObject>();

    ExampleObject one = new ExampleObject();
    ExampleObject two = new ExampleObject();

    list.add(one);
    list.add(two);

    System.out.println(list.indexOf(one)); // '0' as expected
    System.out.println(list.indexOf(two)); // '0', but I want to get '1'

  }
}

My intention: I need a list of objects, where I want to store initialized objects and edit them later.

like image 828
MyPasswordIsLasercats Avatar asked Mar 23 '23 22:03

MyPasswordIsLasercats


1 Answers

Do the iteration yourself, indexOf is just a helper method:

static int indexOfById(List<?> list, Object searchedObject) {
  int i = 0;
  for (Object o : list) {
    if (o == searchedObject) return i;
    i++;
  }
  return -1;
}
like image 78
Marko Topolnik Avatar answered Apr 06 '23 00:04

Marko Topolnik