java - Very Wired thing happens when I compare two elements of the ArrayList -


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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -