Java中equals()与==操作符

一般来说equals()方法是比较两个对象值的。

例如比较两个Integer 对象

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/
ContractedBlock.gif) public class Equalival … {
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) public static void main(String[] args) … {

Integer n1 = new Integer( 47 );

Integer n2 = new Integer( 47 );

System.out.println(n1.equals(n2));
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kEnd.gif) }

打印true

//Thinking in Java中的例子

==操作符是用来比较引用是否相等


public class Equalival
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/
ContractedBlock.gif) … {
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) public static void main(String[] args) … {

Integer n1 = new Integer( 47 );

Integer n2 = new Integer( 47 );

System.out.println(n1 == n2);

System.out.println(n1 != n2);
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kEnd.gif) }

打印false,true

感觉以上的例子并没有说明什么看看下面的这个String的例子:


public class TestRef
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/
ContractedBlock.gif) … {

public static void main(String[] args)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {

String s = new String( " a " );

if (s == " a " )

System.out.println( " true1 " );

if (s.equals( " a " ))

System.out.println( " true2 " );

String ss = " a " ;

if (ss == " a " )

System.out.println( " true3 " );

if (ss.equals( " a " ))

System.out.println( " true4 " );
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kEnd.gif) }

这个打印true2,true3,true4。因为new String时在堆中生成了空间给“a”,对于第一次的s==“a”时,栈分配空间给"a",并把"a"当
成一个匿名的对象。赋值ss=“a”,意味着在栈中分配了空间给"a",并把"a"这个匿名的对象引用赋给ss。,所以s与"a"的引用不等。而"a"再次出现在代码
中时,编译器查找到先前的“a”对象,而不是再分配内存给"a"。所以ss与"a"的引用是相等的。但不管引用是否相等,其值都是"a",这便看出了equals()
的威力。