黑马程序员技术交流社区

标题: 集合问题。。 [打印本页]

作者: 李兆宁    时间: 2012-10-7 17:37
标题: 集合问题。。
  1. import java.util.*;
  2. class Test09
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 TreeSet<Integer> al = new TreeSet<Integer>();
  7.                 al.add(4);
  8.                 al.add(6);
  9.                 al.add(1);
  10.                 al.add(3);

  11.                 Sort.upSort(al);
  12.                 Sort.downSort(al);
  13.         }
  14. }

  15. class Sort
  16. {
  17.         public static void upSort (TreeSet<Integer> al)
  18.         {
  19.                 for (int i=0,n=al.size(); i<n; i++)
  20.                 {
  21.                         System.out.print(al.first()+" ");
  22.                         al.remove(al.first());
  23.                 }
  24.         }

  25.         public static void downSort (TreeSet<Integer> al)
  26.         {
  27.                 for (int i=0,n=al.size(); i<n; i++)
  28.                 {
  29.                         System.out.print(al.first()+" ");
  30.                         al.remove(al.last());
  31.                 }
  32.         }
  33. }
复制代码
这种参数传递,传递的集合,就是传递的对象的引用,两个都指向了这些对象。
从一个集合中移除,另个集合应该不受影响啊,只打印了一遍,说明主函数中的也没了?
求真相。
作者: 徐传任    时间: 2012-10-7 18:01
  1. 1 3 4 6 //运行结果是这个
复制代码
treeSet集合底层是二叉树结构,所以对集合进行了排序,你操作的是同一个集合,所以在你打印的结果都是在upSort方法中打印的,用这个方法后集合中的元素都被删除掉了,所以upSort方法接受后集合已经没有了
集合就像一个面盆,你往里放了很多东西,但是都取出来了,所以这个集合就没有了
作者: 李兆宁    时间: 2012-10-7 18:10
徐传任 发表于 2012-10-7 18:01
treeSet集合底层是二叉树结构,所以对集合进行了排序,你操作的是同一个集合,所以在你打印的结果都是在upS ...

我在另个类传递后,不就相当于又创建了一个面盆吗
作者: 黄小贝    时间: 2012-10-7 18:45
java的传递是引用传递还是值传递困扰了不少人~~

虽然java通过引用操作对象,但是java传递方法参数时传递的是值而不是引用

这里可能有同学要问了,楼主的例子的确是通过引用修改了对象呀~

Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.


java实际上传递的是一个引用的拷贝

举一个例子





让我们来看看原因~

前三行都没有问题,为啥第四行会出现 0,0 的结果,如果是通过引用传递,就应该改动了对象的值呀

原因是当你传了参数过去时,等于复制了一个引用指向同一个对象

如下图,两个引用指向同一个对象,当你通过method reference 修改对象时,对象是真的被改变了~

但是我们的swap函数中让method reference 指向了其他的对象,而我们原来的original reference 指向的对象没有任何变化,当出了函数的时候, method reference 就会被丢弃~~

所以~~第三行出现的原因,我们通过引用改动了对象的值,出函数original reference  指向的 对象变了,打印的值也要变
第四行,我们只是改动了copy reference 的指向,original reference  的指向没有变化,打印的值不变




Java copies and passes the reference by value, not the object.
Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.




原文:http://sunway.iteye.com/blog/202512







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2