考慮以下代碼:
class Student{
int id;
String name;
}
public class Main
{
public static void main(String[] args) {
Student s1 = new Student();
s1.id = 10;
s1.name = "student 1";
Student s2 = new Student();
s2.id = 20;
s2.name = "student 2";
Student s3 = s1;
s3.name = "student 3";
System.out.println(s1.id " " s1.name);
System.out.println(s3.id " " s3.name);
}
}
對于上面的代碼,輸出是:
10 student 3
10 student 3
但是當我使用整數物件、字串物件或其他一些包裝類物件時,輸出是不同的。考慮以下代碼:
public class Main
{
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
Integer c = a;
c = 30;
System.out.println(a);
System.out.println(c);
}
}
上面代碼的輸出是:
10
30
在我的自定義物件中,如果我更改一個物件的值,則兩個物件的值都會更改,但為什么在像 Integer 和 String 這樣的物件中情況并非如此。
我的困惑是參考如何在 Integer、String、Double 等類中作業。
uj5u.com熱心網友回復:
s1 指的是記憶體的一部分,我們稱那部分為 A。將 s1 分配給 s3 后,s3 也將指代 A;這意味著 s1 和 s3 都有指向同一個記憶體塊的指標。更改 s1 或 s3 實際上是更改該記憶體塊中的資料;并將影響兩者。
uj5u.com熱心網友回復:
包裝類是不可變的。這意味著,如果我們想更改包裝類的值,我們別無選擇,只能為參考包裝類的變數分配一個新值。因此,在提供的代碼中,我們創建了三個可訪問的實體Integer(通過自動裝箱):
Integer a = 10; // 1st instance of Integer created
Integer b = 20; // 2nd instance of Integer created
Integer c = a; // still 2 instances, c references the same Integer as a
c = 30; // 3rd instance of Integer created
System.out.println(a);
System.out.println(c);
我們可以通過稍微擴展代碼使其可見:
Integer a = 10; // 1st instance of Integer created
Integer b = 20; // 2nd instance of Integer created
Integer c = a; // still 2 instances, c references the same Integer as a
System.out.println(a == c); // will print "true", a and c reference the same exact Integer
c = 30; // 3rd instance of Integer created
System.out.println(a);
System.out.println(c);
System.out.println(a == c); // will print "false", a and c reference different Integers
Ideone demo
我們可以看到包裝型別的參考沒有得到任何特殊處理。行為(除了自動裝箱的能力)與 Java 中的任何外部參考型別相同。
uj5u.com熱心網友回復:
你在比較蘋果和橙子。
在代碼片段 A
Integer a = 10;
Integer b = 20;
Integer c = a;
c = 30;
你是不是修改通過參考的物件a和c,你分配一個新的參考c。
在代碼片段 B 中
Student s1 = new Student();
s1.id = 10;
s1.name = "student 1";
Student s2 = new Student();
s2.id = 20;
s2.name = "student 2";
Student s3 = s1;
s3.name = "student 3";
您沒有為 分配新的物件參考s3,而是在修改由s1和參考的物件s3。
與代碼片段 A 相當的代碼片段將是
Student s1 = new Student();
s1.id = 10;
s1.name = "student 1";
Student s2 = new Student();
s2.id = 20;
s2.name = "student 2";
Student s3 = s1;
s3 = new Student();
s3.name = "student 3";
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344649.html
下一篇:Heroku無法識別遷移
