”==“和”equals()“ 的纠结

最近参加了几次笔试题,发现基础题考的比较多,有好几家公司都考到了”==“和”equal“s的使用
这是迅雷2011校园招聘的一个选择题:
    What happens when you try to compile and run the following code?
public class EqualsTest {
public static void main(String args[]) {
Long LA = new Long(666);
Long LB =new Long(LA);
long la=LA;
long lb=LB;
System.out.print(LA==LB ? "0":"1");
System.out.print(la!=lb ? "2":"3");
}
}
A.The program compiles but throws a runtime exception in line 7.
B.The program cannot compile because of line 8.
C.The program cannot compile because of line 4.
D.The program compiles and prints "13".
E.The program compiles and prints "03".
F.The program compiles and prints "12".
G.The program compiles and prints "02"

[color=green]一. “=="和”!=“:[/color]

[color=red]上例中最终结果是 :"13"[/color]
虽然两个Long对象实际的都是相同的,然而对象的引用却是不同的,“=="和”!=“比较的是对象的引用(”对象的变量“或者说是”对象储存的地址“)却不是对象的实际本身的内容”666“ 。以及基本类型也是用他们来比较的。
如果出现:
int a=1;
int b=1;
a.equals(b);
编译是通不过的

[color=green]二.equals 的用法:[/color]



class Value{
int i;
}
public class EqualsTest3 {
public static void main(String[] args) {
Value v1=new Value();
Value v2=new Value();
v1.i=v2.i=100;
System.out.println(v1.equals(v2));
}
}

[color=red]输出:false[/color]

其实equals()的默认比较也是比较两个引用的,所以在上面这个实例中相当于”v1==v2“比较,结果当然是false。

[color=red] 只有当在比较的两个对象所属类中覆盖(重写)了老大Object的equals()方法时,才能用equals()来比较两个对象的实际内容:
[/color]

public class EqualsTest3 {

public static void main(String[] args) {

String s1 = new String("abc");
String s2 = new String("abc");

System.out.println(s1.equals(s2));
}
}
结果是:true
为什么呢,看上去这个跟前一个例子相矛盾了 ,其实不然。 看看java给我们提供的类库的String 就知道了 :
 public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
看完这段代码,就知道为什么上例中的结果是 true 了;

如果有需要 我们自己也可以重写老大Object 的equals()的方法从而达到我们的目的:

class Value {
Value(String s) {
}

public boolean equals(Object obj) {
System.out.println("我不管你怎么搞,都不让你们两个相等");
return false;
}
}
public class EqualsTest3 {

public static void main(String[] args) {

Value v1=new Value("a");
Value v2=new Value("a");

System.out.println(v1.equals(v2));
}

}
结果可想而知,呵呵
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值