0

I'm implementing arrayList with array and jumped into a problem with the Object type of data.

this is my indexOf method which runs normally

public int indexOf(Object item) {

        int index = -1;

        for (int i = 0; i < capacity; i++) {

            if (arrayList[i] == item) {

                index = i;

            }
        }

        return index;

    }

but if i have an int number like '1444' in my list and try to run list.indexOf(1444); the method can't find it's index. If I add at the same index another lesser number or a string or anything else it works normally. also I don't have any restrictions about the int type in my code.

  • 4
    Don't compare `Object`s with `==`. Use [`equals(...)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)) instead. – Turing85 Mar 05 '20 at 22:09
  • 1
    Just to clarify @Turing85's comment: `==` checks if 2 **references** are the same and `equals` should be overwritten by subclasses and check wheather the **content** of the objects is the same. `==` will return `false` for two seperate objects(e.g. `Integer`s) containing the same content(number) but `equals` will return `true` in that case. – dan1st Mar 05 '20 at 22:15
  • I would also swap the order to call `item.compareTo(arrayList[i])` instead of `arrayList[i].compareTo(item)` to avoid `NullPointerException`s. – Mateus Bandeira Mar 05 '20 at 22:16
  • 2
    Or even better: use [`Objects.equals(...)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Objects.html#equals(java.lang.Object,java.lang.Object)) (the `s` makes all the difference). – Turing85 Mar 05 '20 at 22:18
  • Thank you so much, the comparison was my problem. Made it to `item.equals(arrayList[i])` and it works normally. – Angel Bloom Mar 05 '20 at 22:18
  • I agree with @Turing85. `Objects.equals(...)` is a better way to go. – Mateus Bandeira Mar 05 '20 at 22:24

0 Answers0