Integer a = new Integer(6);
Integer b = new Integer(6);
Long c = new Long(6);问:
a ==b ?
a.equal(b)?
a ==c ?
a.equal(c)?
a.equal(new Integer(6))?
问:?后面是Y OR N
Integer b = new Integer(6);
Long c = new Long(6);问:
a ==b ?
a.equal(b)?
a ==c ?
a.equal(c)?
a.equal(new Integer(6))?
问:?后面是Y OR N
a.equal(b)?true
a ==c ?不可比较也就是不相等了
a.equal(c)? false
a.equal(new Integer(6))?true
false
true
false
true
Press any key to continue...
equals比较的是值还要你的equals写错了
"=="是比较地址的
"equals"方法是比较内容的
Integer a = new Integer(6);
int b=6;
有什么区别?a==b?
a.equal(b)?
a是对象,b不是对象,只是一个简单的整数。==号的两边一定要是相同的类型;
equals()方法继承自Object类,而Integer类又重写了它,去看一下Integer类的源码就知道了。
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
他们比较的是他们value。希望大家以后不要再搞错了。
Integer a = new Integer(6);
Integer b = new Integer(6);
Long c = new Long(6); System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals(new Integer(6))); }}自己运行看看
a ==c 出错,不用比较肯定N
==和!=运算符比较的是对象的references ;只有当两个references指向相同的对象时才相等;
如果不被覆写,equals()的默认行为和==相同,也是比较references。而对于Integer,String,Long等外覆型别,都对equals()进行了覆写。所以判断equals()执行的结果,还得看覆写后的内容!测试程序:package others;public class EqualsTest { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=new Integer(6);
Integer b=new Integer(6);
Long c=new Long(6);
String s1=new String("6");
String s2=new String("6");
Integer e=a;
class TypeF{
int i;
}
TypeF f1=new TypeF();
TypeF f2=new TypeF();
f1.i=f2.i=6;
System.out.println(a==b);
System.out.println(a.equals(b));
//System.out.println(a==c); throw Unresolved compilation problem Exception
System.out.println(a.equals(c));
System.out.println(a.equals(new Integer(6)));
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(a==e);
System.out.println(f1==f2);
System.out.println(f1.equals(f2));
}}
输出结果:
false
true
false
true
false
true
true
false
false
-----------------
Integer a = new Integer(6);
int b=6;
有什么区别?int是java的基本型别,具有固定的大小,而Integer等是他们相对的外覆类,继承自Object,和其他对象具有相同的效用。