equals方法返回的是boolean值, 功能是对比对象的地址,通过重载方法 当然也可以达到对比某个值的要求: class Value { int i; public boolean equals(Object o){ return (((Value)o).i==i); } } 或者分行来写: public boolean equals(Object o){ int j=0; Value v = (Value)o; j=v.i; if(i==j) return true; return false;
}
可: public class EqualsMethod { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1.equals(n2)); } } 则会输出“true”“equals"是对比两个对象的实际内容是否相同吗? 问题1为何输出”false"??
This is because the default behavior of equals( ) is to compare references. So unless you override equals( ) in your new class you won’t get the desired behavior. Most of the Java library classes implement equals( ) so that it compares the contents of objects instead of their references.明白吗?类Integer 内部已经override了equals方法了,所以就是你看到的这样子.
看来我还是过些天再考SCJP吧,我也不会这个问题
这些问题在《Thinking in Java》书中有详细的介绍,若要靠SCJP,最好还是将这本书通读几遍!
功能是对比对象的地址,通过重载方法
当然也可以达到对比某个值的要求:
class Value {
int i;
public boolean equals(Object o){
return (((Value)o).i==i);
}
}
或者分行来写:
public boolean equals(Object o){
int j=0;
Value v = (Value)o;
j=v.i;
if(i==j) return true;
return false;
}
public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2));
}
}
则会输出“true”“equals"是对比两个对象的实际内容是否相同吗?
问题1为何输出”false"??
Most of the Java library classes implement equals( ) so that it compares the contents of objects instead of their references.明白吗?类Integer 内部已经override了equals方法了,所以就是你看到的这样子.