Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1606229
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: Java

2016-10-14 11:29:52

点击(此处)折叠或打开

  1. public class ArrayTest
  2. {
  3.     //都是引用传递,输出的结果是"goodbbb"
  4.     public void arrayPassTest(String s, String[] ss)
  5.     {
  6.         s = "bad";
  7.         ss[0] = "bbb";
  8.     }
  9. public static void main(String[] args)
  10.     {
  11.         String s1 = new String("good");
  12.         String[] ss1 = {"aaa"}; //string数组,只有一个元素
  13.         
  14.         ArrayTest test = new ArrayTest();
  15.         test.arrayPassTest(s1, ss1);
  16.         System.out.println(s1+ss1[0]);
输出结果:
goodbbb

如果你认为arrayPassTest 函数中,s是作为值传递,而ss是作为引用传递,所以有这样的输出结果,也不算错误,但是决对没有真正理解里面的原因。在这里,String 类型的传递是引用传递,也即是地址传递。这个是毋庸置疑的。因为在java里,String是对象类型,作为参数肯定是引用传递。之所以有值传递的效果,是因为Stirng内部实现时,是用char[] 来存储字符串的,所以String相当于char[]的包装类,那java中,包装类的一个特质就是值操作时体现对应的基本类型的特质。


这个确实有点难理解,尤其是从C/C++转出过的程序员。需要再慢慢揣摩。


ss参数完全符合引用传递的特点,很好理解,不多说。附上String的构造函数实现,


点击(此处)折叠或打开

  1. public String(String original) {
  2.     int size = original.count;
  3.     char[] originalValue = original.value;
  4.     char[] v;
  5.       if (originalValue.length > size) {
  6.       // The array representing the String is bigger than the new
  7.       // String itself. Perhaps this constructor is being called
  8.       // in order to trim the baggage, so make a copy of the array.
  9.      v = new char[size];
  10.       System.arraycopy(originalValue, original.offset, v, 0, size);
  11.      } else {
  12.       // The array representing the String is the same
  13.       // size as the String, so no point in making a copy.
  14.      v = originalValue;
  15.      }
  16.     this.offset = 0;
  17.     this.count = size;
  18.     this.value = v;
  19.     }
这个示例也给我们一个启示,当写一个函数传递数组时,不要直接对内部成员赋值,否则结果就不可控了, 比如下面这个函数,如果myArray被某个成员函数改变了,那么传递的这个数组也会改变。

点击(此处)折叠或打开

  1. public void setArray(String[] newArray)
  2.     {
  3.         this.m_myArray = newArray;
  4.     }

  5. //应该这样实现

  6. public void setArrayNew(String[] newArray)
  7.     {
  8.         if(newArray == null)
  9.         {
  10.             this.m_myArray = new String[0];
  11.         }
  12.         else
  13.         {
  14.             this.m_myArray = new String[newArray.length];
  15.             System.arraycopy(newArray, 0, this.m_myArray, 0, newArray.length);
  16.         }
  17.     }
http://blog.csdn.net/pony_maggie/article/details/44120045

阅读(580) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~