java - Very Wired thing happens when I compare two elements of the ArrayList -
this question has answer here:
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 shown above. , results shown below.
2000 not equal check
2 equal check
the results show me wired things..
i confused... appreciate if can me this.
you shall not compare reference types (anything object) using ==. use equals().
== returns true if 2 object references pointing same object in memory.
given that, problem how integer objects come existence:
while working on source code compiler different things add(2000) , add(2):
for values between -127 , 128 ... compiler not create new integer object, "smart" caching ... add(2) adds same object instance.
therefore reference-equality check using == returns true. add(2000), new object returned each time; therefore == returns false.
Comments
Post a Comment