==比较的是对象的引用,equals() 缺省行为也是比较对象的引用,但绝大多数java类库的类都覆写了equals()方法,会比较对象的内容,
String a = new String("abc");
String b = new String("abc");
String c = "abc";
String d = "abc";
System.out.println(a==b); //false
System.out.println(a.equals(b)); //true
System.out.println(a==c); //false
System.out.println(a.equals(c)); //true
System.out.println(c==d); //true
System.out.println(c.equals(d)); //true
如果对自己创建的类的实例用equals()方法比较的就还是对象的引用,除非你在新类里覆写equals()方法
class Value {
int i;
public Value(int i) {
super();
this.i = i;
}
}
public class EqualsTest {
public static void main(String[] args) {
Value v1 = new Value(10);
Value v2 = new Value(10);
System.out.println(v1.equals(v2)); //false
}
}