Because ArrayList.remove
doesn't use reference identity (which is what you get with ==
) - it uses equals
.
From the documentation:
Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index
i
such that(o==null ? get(i)==null : o.equals(get(i)))
(if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
And equals
will return true:
Integer a = 546;
Integer b = 546;
System.out.println(a.equals(b)); // true
Note that if it didn't use equals
, it would be pretty broken for things like String
as well:
List<String> list = new ArrayList<>();
list.add("foo");
list.remove(new StringBuilder("f").append("oo").toString()));
System.out.println(list.size()); // 0