Indexof() has a strange Java. String with a duplicate string util. List behavior
I've just encountered some strange behavior. I don't expect from ArrayList < string > in Java Of course, this is because of my lack of understanding of references in Java
Let me tell you this Code:
List<String> myList = new ArrayList<>(); myList.add("One"); myList.add("Two"); myList.add("Two"); myList.add("Three"); for (String s : myList){ System.out.println(myList.indexOf(s)); }
This code provides the following output:
0 1 1 3
How? I deliberately added two strings containing the same character ("two"), but the object itself should not be the same What did I misunderstand here? I look forward to this other output:
0 1 2 3
Solution
ArrayList. Indexof () does not use reference equality to find objects It uses the equals () method Pay attention to what the document says (emphasize my):
Therefore, it will match the first string that is logically equal
Edit:
Andremoniy's comments are absolutely correct In the case of string literals, because they are interns, they also happen to have the same reference Therefore, in this case, your two strings "two" are actually the same reference
System.out.println("Two" == "Two"); // will return true because they are the same reference.