一、值传递和引用传递
java在处理基本数据类型时,都是采用值传递(传递的是输入参数的复制);除此之外的其他类型都是按引用传递。值传递时无论如何都不会改变其原值,因为只是参数的复制;而引用传递在赋值时(即=操作)时也不会改变原来的值,只有在改变引用中的值时才会改动传入进来的参数(包括各种容器,它的添加删除元素,都会直接影响到传入的参数)。一些代码示例如下
package java_IO;
public class referece_valueTrans {
public static void f1(int i1,int i2){
i1=i2;
i2++;
}
public static void f2(String s1,String s2){
s1=s2;
}
public static void f3(String s){
s="hello";
}
public static void f4(test t){
t.val=10000;
}
public static void f5(test t1,test t2){
t1=t2;
t1.val=1;
}
public static void f6(int i) {
i++;
}
public static void main(String[] args) {
int i1=1;
int i2=5;
System.out.println("f1前:i1="+i1+",i2="+i2);
f1(i1,i2);
System.out.println("f1后:i1="+i1+",i2="+i2);
String s1="good";
String s2="bye";
System.out.println("f2前:s1="+s1+",s2="+s2);
f2(s1,s2);
System.out.println("f2后:s1="+s1+",s2="+s2);
f3(s2);
System.out.println("f3后:s2="+s2);
test t=new test(0);
System.out.println("f4前:t.val="+t.val);
f4(t);
System.out.println("f4后:t.val="+t.val);
test t1=new test(5);
test t2=new test(10);
f5(t1,t2);
System.out.println("t1.val="+t1.val+",t2.val="+t2.val);
int i=1;
f6(i);
System.out.println(i);
// TODO Auto-generated method stub
}
}
class test{
int val=0;
public test(int value){
val=value;
}
public void setVal(int value){
val=value;
}
}
二、浅复制和深复制。
Cloneable和Serializable都是标识接口(没有任何方法声明的接口)。祖先类Object提供了一个clone方法,这个方法的作用是返回一个Object对象的复制。实现复制的方法及步骤
1)继承Cloneable这个接口
2)在类中重写clone()方法,利用super.clone()即可,注意加异常处理(try catch,可能捕捉到CloneNotSupportedException)
3)把浅复制的引用指向原型对象新的克隆体
浅复制代码
public class CloneTest implements Cloneable {
public int value=0;
public CloneTest(int value){
this.value=value;
}
public void changeValue(int value){
this.value=value;
}
//注意要重写Object里的clone函数
//以下是浅复制
@Override
public Object clone(){
Object o=null;
try{
o=(CloneTest)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return o;
}
/**
* @param args
*/
public static void main(String[] args) {
CloneTest ct=new CloneTest(1);
CloneTest ct1=(CloneTest)ct.clone();
ct1.changeValue(2);
System.out.println(ct.value);
System.out.println(ct1.value);
// TODO Auto-generated method stub
}
}
浅复制指该类里只有基本类型数据的成员。也可以有非基本类型数据的成员,仅仅复制所考虑的对象,而不复制它引用的对象。
而深复制不仅复制所考虑的对象,还要复制它所引用的对象,看一下重写的clone()即可看出区别,代码如下:
//深复制
public class CloneTest1 implements Cloneable {
CloneTest t;
public CloneTest1(CloneTest t){
this.t=t;
}
public CloneTest1 clone(){
CloneTest1 t1=null;
try{
t1=(CloneTest1)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
t1.t=this.t.clone();
return t1;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}