Copying one object to another object produces different results in java

public static void main(String[] args) { Integer a = 1; Integer b = 0; b=a; System.out.println(a); System.out.println(b); ++a; System.out.println(a); System.out.println(b); } 

output: 1 1 2 1

 public static void main(String[] args) { ArrayList<Integer> a = new ArrayList<Integer>(); ArrayList<Integer> b = new ArrayList<Integer>(); a.add(1); a.add(1); a.add(1); a.add(1); b=a; System.out.println(a.size()); System.out.println(b.size()); b.add(2); System.out.println(a.size()); System.out.println(b.size()); } 

output: 4 4 5 5

For the code above, why both objects do not belong to the same memory location.

+5
source share
5 answers

Case -1:

 public static void main(String[] args) { Integer a = 1; Integer b = 0; b=a; // 2 references a and b point to same Integer object System.out.println(a); System.out.println(b); ++a; // now a references to a new integer object with value 2 where as b refers to old integer object with value 1 System.out.println(a); System.out.println(b); } 

Case 2:

And again, both a and b reference and work on the same arrayList instance. Therefore, a change using one link is reflected in other links.

+1
source

This is because Integer is immutable. After creating it, you cannot change it. If you want the value to change, it will point to a new memory location. When you do ++a , a will become a new object.


It might be easier if you look at it from a String perspective. (The string is also immutable)

  String s1 = "aaa"; String s2 = s1; s1 = "bbb"; System.out.println("s1: " + s1); System.out.println("s2: " + s2); 

CONCLUSION:

 s1: bbb s2: aaa 
+3
source

All wrapper classes are actually immutable in Java. We know that String is a well-known immutable class. In addition to this, other wrappers, such as Integer, are also immutable.

See http://www.javaworld.com/article/2077343/learn-java/java-s-primitive-wrappers-are-written-in-stone.html

+3
source
  Integer a = 1; Integer b = 0; b=a; System.out.println(a); System.out.println(b); if(a == b){ System.out.println("Both objects are equal"); } ++a; if(a != b){ System.out.println("Both objects are different"); } System.out.println(a); System.out.println(b); 
+2
source

++a creates a new object =a+1 , and then sets a = this new object. b does not change because assignment does not affect the object contained in the reassigned variable.

On the other hand, .add(2) adds 2 to the list indicated by a , which is the same link as the specified b , since they were equal.

0
source

Source: https://habr.com/ru/post/1214536/


All Articles