== :
1.基本数据类型:根据基本数据类型的值判断是否相等,相等返回true,反之返回false
注意:两端数据类型可以不同, 在不同的情况下,也可以返回true
2.引用数据类型:Object obj1 = newObject(); 比较引用类型变量的地址值是否相等
Object obj2= newObject();
system.out.println(obj1 == obj2)//false
TestEquals:
package com.aff.equals; import com.aff.java1.Person; public class TestEquals { public static void main(String[] args) { // == int i = 12; int j = 12; System.out.println(i == j);// true char c = 12; System.out.println(i == c);// true float f = 12.0f; System.out.println(i == f);// true int k = 65; char a = 'A'; System.out.println(k == a);// true Object obj1 = new Object(); Object obj2 = new Object(); System.out.println(obj1); System.out.println(obj2); System.out.println(obj1 == obj2);// false Person p1 = new Person(); Person p2 = new Person(); Person p3 = p1; System.out.println(p1 == p2);// false System.out.println(p1 == p3);// true System.out.println("---------------------分割线-------------------------"); // equals():①只能处理引用类型变量 // ②在Object类,发现equals()仍然比较的两个引用变量的地址值是否相等 // java.lang.Object类,是所有类的根父类 Person p5 = new Person(); Person p6 = new Person(); System.out.println(p5.equals(p6));// false-->true 重写了Person的equals方法 System.out.println(p5 == p6);// false // 像String 包装类 File类 Date类这些重写Object类的equals()方法,
//比较是两个对象的实体内容是否完全相同 String str1 = new String("AA"); String str2 = new String("AA"); System.out.println(str1 == str2);// false System.out.println(str1.equals(str2));// true } }
输出结果:
true
true
true
true
java.lang.Object@6d06d69c
java.lang.Object@7852e922
false
false
true
---------------------分割线-------------------------
true
false
false
true
Person:重写equals方法:
package com.aff.java1; public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void walk() { System.out.println("走路"); } public void eat() { System.out.println("吃"); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } /* public boolean equals(Object obj) { return true; } */ }