Topic: 关于equals()方法的困惑 |
Print this page |
1.关于equals()方法的困惑 | Copy to clipboard |
Posted by: zmj888 Posted on: 2005-12-08 12:51 class Triple1 { private int x1,x2,x3; public Triple1(){ this(0,0,0); } public Triple1(int a,int b,int c){ setValue(1,a); setValue(2,b); setValue(3,c); } public void setValue(int i,int value){ switch( i ){ case 1:x1=value;return; case 2:x2=value;return; case 3:x3=value;return; default: System.err.println("error"); System.exit(1); } } } class triple{ public static void main(String args[]){ Triple1 h=new Triple1(1,1,1); Triple1 t=new Triple1(1,1,1); System.out.println(h.equals( t )); // System.out.println(h=t); System.out.println(h==t); } } 上面代码运行结果是 false false 为什么加入红色那段代码运行结果就变了呢 false Triple1@757aef ture |
2.Re:关于equals()方法的困惑 [Re: zmj888] | Copy to clipboard |
Posted by: ntshenwh Posted on: 2005-12-08 13:11 hi, your code seems not correct. I updated these as follows: class triple { private int x1,x2,x3; public triple() { this(0,0,0); } public triple(int a,int b,int c) { setValue(1,a); setValue(2,b); setValue(3,c); } public void setValue(int i,int value) { switch( i ) { case 1:x1=value;return; case 2:x2=value;return; case 3:x3=value;return; default: System.err.println("error"); System.exit(1); } } public static void main(String args[]) { triple h=new triple(1,1,1); triple t=new triple(1,1,1); System.out.println(h.equals( t )); System.out.println(h==t); } } // here , both equals() and == are all compare the reference of objects. the result is false false good luck |
3.Re:关于equals()方法的困惑 [Re: zmj888] | Copy to clipboard |
Posted by: zmj888 Posted on: 2005-12-08 13:40 thank you |
4.Re:关于equals()方法的困惑 [Re: zmj888] | Copy to clipboard |
Posted by: andykid Posted on: 2005-12-08 20:19 个人理解,黙认的equals()方法是比较引用(在java中绝大部分内置的类都重载了equals()方法,使其比较值),在Triple1类中没有重载equals()方法,所以在System.out.println(h.equals( t ));是比较引用,显示为false, 加入红色部分的System.out.print(h=t),h和t的引用一样了。所以再接下来的 System.out.println(h==t); 显示为true,因==是比较引用。 |
5.Re:关于equals()方法的困惑 [Re: zmj888] | Copy to clipboard |
Posted by: yangyuming Posted on: 2005-12-11 15:47 System.out.print(h=t)表示输出一个引用,因为没有重载toString方法,所以默认输出类名@标识码 |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |