public class Pass {    
  public void setValue(int[] ab) {    
    ab[0] = 0;
    ab[1] = 1;
    ab = null;
  }    
  
  public static void main(String[] args) {   
Pass pass = new Pass();
int[] ab = new int[2];
ab[0] = 3;
ab[1] = 4;
pass.setValue(ab);
System.out.println(ab[0]);
System.out.println(ab[1]);
  }    
}    //猜猜结果输出的是什么?

解决方案 »

  1.   

    方法setValue中的ab是一个引用(main中的ab)的拷贝,与main中的ab一样,
    都是指向同一个数组因此
    ab[0]=0;
    ab[1]=1;
    就会修改指向的数组元素。而ab=null,也仅仅是将这个引用的拷贝设置为null,它
    现在不指向任何东西,可数组还在那里,被main中的引用ab指向着验证了:java的参数传递是传值,
    对于基本类型,就是值的拷贝,对于引用类型,就是引用的拷贝。
      

  2.   

    当然是0 ,1。这个哪里需要猜!    ab[0] = 0;//这里改变的是ab所指向对象中的内容,所以外部的ab也会产生变化
        ab[1] = 1;
        ab = null;//这里改变的是ab的指向,ab已经指向了null,但是外部的ab指向不发生变化,原对象的值并没有发生变化
      

  3.   

    side effect, bad design
      

  4.   

    killme2008(www.rubyeye.net):
    "可数组还在那里,被main中的引用ab指向着"
    这句话没有说得太清晰ChDw(米):
    "这里改变的是ab所指向对象中的内容,所以外部的ab也会产生变化"
    这句话也感觉稍稍有点问题main中的ab其实一直都没有变化,变化的只是它们所指向的内容
      

  5.   

    下面这个为什么没有发生改变,请赐教public class Pass {
        public void setValue(String str1) {
            
            System.out.println("str1 = "+str1);
            str1 = "2222";
            System.out.println("str1 = "+str1);
            str1 = null;
        }    public static void main(String[] args) {
            Pass pass = new Pass();
            String str = "111";
            System.out.println("before setValue str is " + str);
            pass.setValue(str);
            System.out.println("acton setValue str is " + str);
        }
    }
      

  6.   

    java中的String是immutable的,每一次改变字符串都是新生成一个String实例
      

  7.   

    java中的String是immutable的,每一次改变字符串都是新生成一个String实例
    ----------------------------------------------------------------------
    正解,相当于每次赋值都new了一个新的String出来
      

  8.   

    每次赋值都new了一个新的String出来
    比如
    string str1="111";
           str1="222";
    执行这两句的意思是,在内存新new一个区域给“222”,然后str1是指向那个新的内存区“222”,而原来的内存区“111”就成为垃圾了