Question

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??

Was it helpful?

Solution

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

OTHER TIPS

Because the correct way to compare objects is using equals:

Integer a=546;
Integer b=546;
System.out.println(a.equals(b));

And that's what is used by ArrayList.

By the way, if you create a new class, you have to write your own equals method in order to work properly.

a==b works on absolute memory locations. if a,b point to the same memory location it returns true. however remove() method works on the equals implementation. since according to equal method every Integer instance with value 546 is equal to anyother, that value is removed from list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top