1.既可判断基本类型,也可以判断引用类型2.基本:判断值是否相等
int a = 10; double d = 10.0; boolean c; c = a==d; System.out.println(c); //true
3.引用:判断地址是否相等
class B {} class A extends B {} A a = new A(); A b = a; A c = b; System.out.println(a==c);//true System.out.println(b==c);//true B obj = a; System.out.println(obj==c);//true
equals是Object类中的方法,只能判断引用类型
默认判断地址是否相等,子类中往往重写该方法,用于判断内容是否相等。例如Integer、String
//equals Object源码 public boolean equals(Object obj) { return (this == obj); //String类重写equals 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; } //比较俩个字符串值是否相同 "hello".equals("abc");//false ----------------------------------------------------------------------------------------- Integer integer1 = new Integer(1000); Integer integer2 = new Integer(1000); System.out.println(integer1==integer2);//false System.out.println(integer1.equals(integer2));//true String s1 = new String("ssy"); String s2 = new String("ssy"); System.out.println(s1==s2);//false System.out.println(s1.equals(s2));//true
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)