My question is: when I create a new Integer using the new Integer (i), can I compare integers using ArrayList.contains ()? That is, when I create a new object using the new Integer (i), will it be the same as the previously created Integer object, if the int value used to create them is the same?
The short answer is yes.
Long answer:
That is, when I create a new object using the new Integer (i), will it be the same as the previously created Integer object, if the int value used to create them is the same?
I assume that you mean "... it will be the same instance as ..."? The answer to this question is: no - calling new will always create a separate instance separately from the previous instance, even if the constructor options are identical.
However, despite having a separate identity, these two objects will have an equivalent value, that is, calling .equals () between them will return true.
Collection.contains ()
It turns out that having separate instances of the equivalent value (.equals () returns true) is fine. The .contains() method is in the Collection interface. The Javadoc description for .contains() reads:
http://java.sun.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)
boolean contains (Object o)
Returns true if this collection contains the specified item. More formally, it returns true if and only if this collection contains at least one element e such that (o == null? E == null: o.equals (e)).
That way, he will do what you want.
Data structure
You should also consider if you have the correct data structure.
Is the list purely protection? important order? Are you worried about duplicates? Since a list is an order, using a list may mean that your code takes care of the order. Or that you need to maintain duplicates in the data structure.
However, if the order is not important, if you do not want or will not have duplicates, and if you really use this data structure only to check whether it contains a certain value, then you might think about whether you should use Set instead.