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); //打印false14 System.out.println(animal1.equals(animal2)); //打印false15 16 System.out.println(animal1==animal3); //打印true17 System.out.println(animal1.equals(animal3)); //打印true18 19 /**20 * String,Date,Integer,Double的equals()已被覆盖,比较规则:21 * 如果两个对象的类型一致,并且内容一致,则返回true22 * 23 * 此时,==和equals()区别总结:24 * ==:比引用,一样为true25 * ==:比数据类型和内容一样为true26 */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);//打印false35 System.out.println(int1.equals(int2));//打印true36 37 System.out.println(str1==str2);//打印false38 System.out.println(str1.equals(str2));//打印true39 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"); //打印a48 else49 System.out.println("b");50 else51 if(obj.equals(b1))52 System.out.println("c");53 else54 System.out.println("d");