首页 > 代码库 > 如何理解java的引用传递

如何理解java的引用传递

 

1. 数组的引用传递
public class TestArray {
    public  static void  changeAry1(int[] ary){
        int[] ary1 = {9,9,9};
        ary = ary1;
    }
    public  static void  changeAry2(int[] ary){
        ary[0] = 100;
    }    
    public static void main(String[] args) {
        int[] ary = {1,2,3};
        System.out.println(Arrays.toString(ary));
        changeAry1(ary);
        System.out.println(Arrays.toString(ary));
        changeAry2(ary);
        System.out.println(Arrays.toString(ary));
    }    
}
View Code

 

 

2. 对象的引用传递
public class TestObject {
    public static void change1(Person p){
        p = new TestObject().new Person();
        p.age= 100;
        p.name = "Lily";
    }
    public static void change2(Person p){
        Person pNew = new TestObject().new Person();
        pNew.age= 200;
        pNew.name = "Mary";
        p = pNew;
    }
    public static void change3(Person p){
        p.age= 200;
        p.name = "Tomy";
    }
    public static void main(String[] args) {
        Person p = new TestObject().new Person();
        p.age = 50;
        p.name="John";
        change1(p);
        System.out.println(p);
        change2(p);
        System.out.println(p);
        change3(p);
        System.out.println(p);
    }
    class Person{
        private int age;
        private String name;
        public String toString(){
            return this.age+","+this.name;
        }
    }
}
View Code

 

3. 再写一个jdk自带类的引用传递
public class TestOtherObject {
    public static void change1(List list){
        list = null;
    }
    public static void change2(List list){
        list.add(null);
    }
    public static void main(String[] args) {
        List list = new ArrayList();
        change1(list);
        System.out.println(list.size());
        change2(list);
        System.out.println(list.size()); 
    }
}
View Code

 

4. 字符串也是引用类型,也是引用传递
public class TestString {
    public static void changeStr1(String str){
        String newValue = "changeValue";
        str = newValue;
        // 或者直接str = "changeValue"; 也是一样
    }
    public static String changeStr2(String str){
        str = "changeValue";
        return str;
    }
    
    public static void main(String[] args) {
        String str = "hello";
        System.out.println(str);
        changeStr1(str);
        System.out.println(str);
        str = changeStr2(str);
        System.out.println(str);
    }
}
View Code