`
len
  • 浏览: 41788 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论
  • len: 假如我不能,我就一定要,假如我一定要,我就一定能!
    生&活

Object类的equals()

    博客分类:
  • Java
阅读更多
public class TestEquals {
	public static void main(String[] args) {
		Cat c1 = new Cat(1, 2, 3);
		Cat c2 = new Cat(1, 2, 3);
		System.out.println(c1 == c2);
		System.out.println(c1.equals(c2));
		
		String s1 = new String("hello");
		String s2 = new String("hello");
		System.out.println(s1 == s2);	// false
		System.out.println(s1.equals(s2)); // true
	}
}

class Cat {
	int color;
	int height, weight;
	
	public Cat(int color, int height, int weight) {
		this.color = color;
		this.height = height;
		this.weight = weight;
	}
	
	public boolean equals(Object obj) {
		if(obj == null) return false;
		else{
			if(obj instanceof Cat) {
				Cat.c = (Cat)obj;
				if(c.color == this.color && c.height == this.height 
&& c.weight == this.weight) {
					return true;
				}
			}
		}
		return false;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics