Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7565934
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: Java

2012-04-16 21:24:25


点击(此处)折叠或打开

  1. public class TestEquals {
  2.     public static void main(String[] args) {
  3.         Cat c1 = new Cat(1, 2, 3);
  4.         Cat c2 = new Cat(1, 2, 6);
  5.         System.out.println(c1 == c2);
  6.         System.out.println(c1.equals(c2));
  7.         
  8.         String s1 = new String("hello");
  9.         String s2 = new String("hello");
  10.         System.out.println(s1 == s2);
  11.         System.out.println(s1.equals(s2));
  12.     }
  13. }

  14. class Cat {
  15.     int color;
  16.     int height, weight;
  17.     
  18.     public Cat(int color, int height, int weight) {
  19.         this.color = color;
  20.         this.height = height;
  21.         this.weight = weight;
  22.     }
  23.     
  24.     public boolean equals(Object obj) {
  25.         if(obj == null) return false;
  26.         else {
  27.             if(obj instanceof Cat) {
  28.                 Cat c = (Cat)obj;
  29.                 if(c.color == this.color && c.height == this.height && c.weight == this.weight) {
  30.                     return true;
  31.                 }
  32.             }
  33.         }
  34.         
  35.         return false;
  36.     }
  37.     
  38. }

阅读(1275) | 评论(0) | 转发(1) |
0

上一篇:Java toString方法

下一篇:Java 对象转型

给主人留下些什么吧!~~