文章字数:446,阅读全文大约需要1分钟
值传递引用传递
1 2 3 4 5 6
| public static void main(String[] args) { String test="test1"; Ob that=new Ob(); that.changeTest(test); System.out.println("test = " + test); }
|
1 2 3
| public void changeTest(String test){ test="test2"; }
|
结果:函数内的改变对外部变量无影响
函数内实参是值传递,即不会对原有对象造成影响
但是,如果传递的是一个对象(本质上是对象的引用地址)就会改变对象,因为即使是值传递,但是传递的地址指向是同一个对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public static void main(String[] args) { te a =new te(); te b = a; a.setName("aaa"); b.setName("bbb"); System.out.println("a.getName() = " + a.getName()); System.out.print("a==b? "); System.out.println(a==b); System.out.println("a = " + a); System.out.println("b = " + b); }
|
内部类
1 2 3 4 5 6 7 8 9 10 11
| class te{ private String name;
public String getName(){ return this.name; }
public void setName(String name){ this.name=name; } }
|
输出结果
1 2 3 4
| a.getName() = bbb a==b? true a = te@3f91beef b = te@3f91beef
|
拓展
这让我想起了之前看到的一个知识点,==
和Object.equals()
的区别。
==
判断的是地址是否相同
Object.equals()
是用来判断对象是否相同的方法,内部默认调用的是==
来判断。
1 2 3 4 5
| public static void main(String[] args) { Ob a = new Ob (); Ob b = new Ob (); System.out.println("a.equals(b) = " + a.equals(b)); }
|
结果
如果没有重写equals()
,即使使用同一个类的构造方法也显示不同。
重写equals()
代码的同时也要重写hashCode()
方法,因为要保证equals
相等,hashCode
一定相等。避免重写equlas()
后达到一定条件对象相等,但是hashCode()
没变。
hashCode()
:hash->简单的说就是一种将任意长度的消息压缩到某一固定长度的消息摘要的函数。hashMap也是将key转换成hash存储,如果hashCode相同,则会在同一个节点用链表存储。通过hashCode找到位置,equals获取两个之一。
附 String类重写equals()
和hashCode()
的源码(1.8)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
|
1 2 3 4 5 6 7 8 9 10 11 12
| public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value;
for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
|