In Integer Wrapper classes ,whenever we compare like this
Integer a=546;
Integer b=546;
System.out.println(a==b);
it returns false,but then why when there is a collection
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(5);
a.add(546);
Integer g=546;
a.remove(g);
it removes it from the ArrayList??
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
See more on this question at Stackoverflow