码迷,mamicode.com
首页 > 编程语言 > 详细

如何理解java的引用传递

时间:2014-05-08 09:21:18      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

 

bubuko.com,布布扣
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

 

 

bubuko.com,布布扣
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

 

bubuko.com,布布扣
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

 

bubuko.com,布布扣
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

 

如何理解java的引用传递,布布扣,bubuko.com

如何理解java的引用传递

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/jianglong-liang/p/3714944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!