java ==、equals()、hashcode() 使用
***********************
==、equals()
==:比较的数据可为基本数据类型、引用类型
若为基本数据类型(如:int、char等),则比较数据的值是否相等;
若为引用类型(如:字符串、对象),则比较数据的内存地址是否相同
equals():比较的数据为引用类型
默认比较数据的内存地址是否相同;重写后可比较数据内容是否相等
***************
示例
class Person{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
class People{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof People)) return false;
People people = (People) o;
return Objects.equals(getName(), people.getName()) &&
Objects.equals(getAge(), people.getAge());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAge());
}
}
public class Test2 {
public static void main(String[] args){
int a=10;
int b=20;
int c=20;
System.out.println("a==b:"+(a==b));
System.out.println("b==c:"+(b==c));
System.out.println("\n**********************");
Person person=new Person();
person.setName("瓜田李下");
person.setAge(20);
Person person2=new Person();
person.setName("瓜田李下");
person.setAge(20);
System.out.println("person == person2:"+(person == person2));
System.out.println("person.equals(person2):"+(person.equals(person2)));
System.out.println("\n**********************");
People people=new People();
people.setName("海贼王");
people.setAge(20);
People people2=new People();
people2.setName("海贼王");
people2.setAge(20);
System.out.println("people == people2:"+(people == people2));
System.out.println("people.equals(people2):"+(people.equals(people2)));
}
}
控制台输出
a==b:false
b==c:true
**********************
person == person2:false
person.equals(person2):false
**********************
people == people2:false
people.equals(people2):true
***********************
equals()、hashcode()
equals()返回true:hashcode()返回的值相等;
equals()返回false:hashcode()返回的值可相等、也可不等
hascode()返回的值不等,equals()返回false
Object
public class Object {
@HotSpotIntrinsicCandidate
public Object() {}
*************
hashcode()
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code equals} comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
//同一个对象多次调用hashcode(),返回的值相同,不会改变
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
//如果两个对象调用equals()返回true,则对象的hashcode相等
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
//如果两个对象调用equals()返回false,则对象的hashcode可相等,也可不等
//建议为不同的对象设置不同的hashcode,提高hash结构中的操作效率
* </ul>
*
* @implSpec
* As far as is reasonably practical, the {@code hashCode} method defined
* by class {@code Object} returns distinct integers for distinct objects.
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
@HotSpotIntrinsicCandidate
public native int hashCode();
*************
equals()
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
//equals()由非null对象调用
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
//x.equals(x)返回true
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
//如果x.equals(y)返回true,则y.equals(x)返回true
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
//如果x.equals(y)返回true,y.equals(z)返回true,则x.equals(z)返回true
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
//在不修改x、y的前提下,多次调用x.equals(y)返回的结果相同
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
//非null的值x,x.equals(null)返回false
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
//重写equals()时,通常需要重写hashcode(),以保证equals()为true时,返回相同的hashcode
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) { //如果不重写equals(),默认比较对象的内存地址
return (this == obj);
}
***************
示例
class MyObject{
private int hashcode;
public MyObject(int hashcode){
this.hashcode=hashcode;
}
@Override
public boolean equals(Object o) {
return true;
}
@Override
public int hashCode() {
return hashcode;
}
}
public class Test3 {
public static void main(String[] args){
MyObject object=new MyObject(1);
MyObject object2=new MyObject(2);
System.out.println("object.equals(object2):"+object.equals(object2));
System.out.println("object.hashcode():"+object.hashCode());
System.out.println("object2.hashcode():"+object2.hashCode());
}
}
控制台输出
object.equals(object2):true
object.hashcode():1
object2.hashcode():2
说明:equals()、hanhcode()约束规则使用时不做检查,仅为提高hash结构操作效率