-1

Today I found strange thing about ArrayList. For the following program:

    ArrayList<Integer> al = new ArrayList<Integer>();
    al.add(128);
    al.add(128);
    int t1 = al.get(0);
    int t2 = al.get(1);
    if(al.get(0)== al.get(1))
      System.out.print("true");
    else
      System.out.print("false");
    if(t1== t2)
      System.out.print("true");
    else
      System.out.print("false");

It it is giving result as falsetrue. For value less than 128, it is giving truetrue. I don't understand what is the logic behind it?

Mmohits
  • 201
  • 1
  • 2
  • 10

1 Answers1

1

The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused.

Hiren
  • 1,427
  • 1
  • 18
  • 35