java中的equals方法与"=="运算符解说

在编程的时候,我们可能经常会用到equals方法,那么这个equals方法和运算符“==”有什么样的区别?

public class equal {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Cat c1=new Cat(1,2,3);
		Cat c2=new Cat(1,2,3);
		System.out.println(c1.equals(c2));
		System.out.println(c1==c2);
		
		String s1=new String("HelloWorld");
		String s2=new String("HelloWorld");
		System.out.println(s1.equals(s2));
		System.out.println(s1==s2);

	}

}

class Cat{
	int color;
	int height;
	int weight;
	
	public Cat(int color,int height,int weight){
		this.color=color;
		this.height=height;
		this.weight=weight;
	}
}

  这是一个很简单的程序,就足以看出两者的区别。程序运行的答案是 false,false,true,false. 为什么?

1、equals方法是属于Object类的,没有被重写之前,它比较的是两个对象的引用,只有当这两个引用指向的是同一个对象的时候,才是equals的,否则就不是!那么运算符“==”也是这样的原理,比较的是引用。因此前两个答案是false,false.最后一个答案也是false.

2、为什么第三个答案是true呢?因为sun公司在创造String类的时候,已经将它的equals方法重写了,只要是字符序列相同的两个String对象,它们就是equals的,因此答案三输出了true!

 

请大家多多补充指正,共同进步!!!

posted @ 2016-03-23 22:04  邱进宝  阅读(249)  评论(0编辑  收藏  举报