Why does this code print Index = 0 for b and s ?

 import java.util.ArrayList; public class Arr { public static void main(String[] args) { ArrayList<String> myList = new ArrayList<>(); String s = new String(); myList.add(s); String b = new String(); myList.add(b); int idx = myList.indexOf(b); System.out.println("Index b=" + idx); int idx2 = myList.indexOf(s); System.out.println("Index s=" + idx2); } } 

    1 answer 1

    In the ArrayList.indexOf() method, the object comparison is implemented as follows

     int indexOf(Object o) { for (int i = 0; i < size(); i++) { if (o == null) { if (get(i) == null) return i; } else { if (o.equals(get(i))) return i; } } return -1; } 

    Since the variables a and b are empty lines,

     a.equals(b) == true 

    That is, from the point of view of the list, there are two identical objects in the list. So the indexOf method returns the index of the first one.

    • Only the indexOf method indexOf n't care if one is an object or two different ones (by the way, there are two different ones) —the equals are compared ... - Alex Chermenin
    • one
      Objects will still be different. - Nofate 2:19 pm
    • one
      @AlexChermenin @ Nofate ♦ Stirlitz has never been so close to failure. Thanks for the kick. Reply rewrote - Anton Shchyrov