-1
public static void main(String[] args) {
    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.add(2000);
    myList.add(2000);
    myList.add(2);
    myList.add(2);

    if(myList.get(1)==myList.get(0))System.out.println("2000 equal check");
    if(myList.get(1)!=myList.get(0))System.out.println("2000 not equal check");
    if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
    if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");
}

My code is shown above. And the results are shown below.

2000 not equal check

2 equal check

The results show me very wired things..

I am really confused... I appreciate if somebody can help me with this.

dsh761
  • 11
  • 1
  • 1
    Please read about [how to ask good questions](//stackoverflow.com/help/how-to-ask) and try to edit your question. With high quality questions you will receive better answers faster. Thanks! – Tobi Nary Jan 27 '16 at 08:03

2 Answers2

2

You shall not compare reference types (anything that is an Object) using ==. Always use equals().

== returns true if the two Object references are pointing to the same object in memory.

Given that, the problem is how the Integer objects come into existence:

while working on your source code the compiler does different things for add(2000) and add(2):

For values between -127 and 128 ... the compiler will actually not create a new Integer object, but do some "smart" caching ... so add(2) always adds the SAME object instance.

Therefore the reference-equality check using == returns true. For add(2000), a new object is returned each time; therefore == returns false.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    "`new Integer(2) == new Integer(2) ` will always be TRUE" say ***WHAT***? [No it doesn't, that expression always returns FALSE] You'd better try that and then rewrite your answer. – Erwin Bolwidt Jan 27 '16 at 08:20
  • 1
    Note: `new Integer(2)` is also *not* what happens when the OP does `myList.add(2);` – Erwin Bolwidt Jan 27 '16 at 08:26
  • You are correct; seems like I was half asleep when writing that down yesterday. Fixed; thank you! – GhostCat Jan 28 '16 at 10:15
1

You are working with Integer objects and thus, you should use .equals().

if(myList.get(1).equals(myList.get(0)))
     System.out.println("2000 equal check");
if(!myList.get(1).equals(myList.get(0)))
     System.out.println("2000 not equal check");
// works because of: see link in the comments to your question
if(myList.get(2)==myList.get(3))System.out.println("2 equal check");
if(myList.get(2)!=myList.get(3))System.out.println("2 not equal check");

The link from the comment section of your question.

Community
  • 1
  • 1
LordAnomander
  • 1,103
  • 6
  • 16