Java中的等號賦值
Java的內存處理分爲堆和棧,將基本變量(int , long, String變量值)存儲在棧中,將對象指向堆的地址放在棧中,這就是說,如果對基本類型做等號賦值,就直接在棧中開闢內存空間存儲,但對對象卻只是重新開闢空間存儲之前對象的地址。
如下代碼給出說明
class Test
{
public static void main(String arg[])
{
String s = "Brother Xiang";
String t = s;
t = t + " is very handsome!";
System.out.println(s);//輸出爲Brother Xiang
System.out.println(t);//輸出爲Brother Xiang is very handsome!
}
}
說明將s, t 對應不同的String對象,修改t時不會影響s的值,以下爲對對象的賦值
class Student
{
private String name;
private int age;
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public void setName(String name)
{
this.name = name;
}
public String toString()
{
StringBuilder s = new StringBuilder();
s.append("Name: " + name + " " + "Age: " + age);
return s.toString();
}
}
class Test
{
public static void main(String arg[])
{
Student student1 = new Student("Bob", 14);
Student student2 = student1;
student2.setName("Jhon");
System.out.print("student1: ");
System.out.println(student1);
System.out.print("student2: ");
System.out.println(student2);
}
}
執行結果爲
可以看出,修改student2同時也修改了student1,這說明只賦值了對對象的引用
Java中淺拷貝與深拷貝
Java當中淺拷貝和深拷貝都是對於對象級別的來說的,淺拷貝和深拷貝的不同由如下代碼就能看出
淺拷貝與深拷貝的簡單形式
//淺拷貝只在Student類上加上Cloneable接口
//深拷貝則需要在Address類與Student類加上Cloneable接口
class Address
{
private String province;
private String city;
public Address(String province, String city)
{
this.province = province;
this.city = city;
}
public void setProvince(String province)
{
this.province = province;
}
public void setCity(String city)
{
this.city = city;
}
public String toString()
{
StringBuilder s = new StringBuilder();
s.append("Location at: " + province + " " + city);
return s.toString();
}
}
class Student implements Cloneable
{
private String name;
private int age;
private Address address;
public Student(String name, int age, Address address)
{
this.name = name;
this.age = age;
this.address = address;
}
public void setName(String name)
{
this.name = name;
}
public Address getAddress()
{
return address;
}
public String toString()
{
StringBuilder s = new StringBuilder();
s.append("Name: " + name + " " + "Age: " + age + " "+ address);
return s.toString();
}
public Student clone()
{
Student temp = null;
try
{
temp = (Student)super.clone();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
return temp;
}
}
class Test
{
public static void main(String arg[])
{
Address address = new Address("GuangDong", "GuangZhou");
Student student1 = new Student("Bob", 14, address);
Student student2 = student1.clone();
student2.setName("Jhon");
Address student2_address = student2.getAddress();
student2_address.setProvince("GuiZhou");
student2_address.setCity("GuiYang");
System.out.print("student1: ");
System.out.println(student1);
System.out.print("student2: ");
System.out.println(student2);
}
}
//它們兩個具體區別在於,淺拷貝通過address訪問Address類中方法時,student2的address發生改變,student1也發生改變,而深拷貝卻不會發生改變,本代碼僅給出淺拷貝的實現方式。
輸出結果如下:
對對象的名字和地址進行改變時,其值也相應發生了改變,
淺拷貝與深拷貝的Serializable形式
傳送門(轉載鏈接):快樂燕子會飛——java serializable深入瞭解