1 /** 2 * Object类的equals()的声明规则: 3 * public Boolean equals(Object obj) 4 * 5 * Object类的equals()方法比较规则: 6 * 当参数obj引用的对象与当前对象为同一对象时,返回true,否则范围false 7 */ 8 9 Animal animal1 = new Dog(); 10 Animal animal2 = new Cat(); 11 Animal animal3 = animal1; 12 13 System.out.println(animal1==animal2); //打印false 14 System.out.println(animal1.equals(animal2)); //打印false 15 16 System.out.println(animal1==animal3); //打印true 17 System.out.println(animal1.equals(animal3)); //打印true 18 19 /** 20 * String,Date,Integer,Double的equals()已被覆盖,比较规则: 21 * 如果两个对象的类型一致,并且内容一致,则返回true 22 * 23 * 此时,==和equals()区别总结: 24 * ==:比引用,一样为true 25 * ==:比数据类型和内容一样为true 26 */ 27 28 Integer int1 = new Integer(1); 29 Integer int2 = new Integer(1); 30 31 String str1 = new String("Hello"); 32 String str2 = new String("Hello"); 33 34 System.out.println(int1==int2);//打印false 35 System.out.println(int1.equals(int2));//打印true 36 37 System.out.println(str1==str2);//打印false 38 System.out.println(str1.equals(str2));//打印true 39 40 /** 41 * 注意:类型转换之后,引用的地址不变 42 */ 43 Boolean b1 = new Boolean(true); 44 Object obj = (Object)b1; 45 if(obj == b1) //强转之后,obj和b1的地址不变 46 if(obj.equals(b1)) 47 System.out.println("a"); //打印a 48 else 49 System.out.println("b"); 50 else 51 if(obj.equals(b1)) 52 System.out.println("c"); 53 else 54 System.out.println("d");