== 和 equals()的区别:
1、==作用于基本数据类型,是比较“值”
2、equals作用于引用数据类型,其比较存于堆区对象所对应的栈区内存地址。
Hashcode()和equals()此法一般用于集合 (最典型的set集合 “唯一性”)
1、重写hashCode方法是确保相等的对象具有相同hash值,因为hashCode是由地址演算得到的,不重写两个相等的对象的hashCode会不一样。equals方法用于比较对象的内容是否相等(覆盖以后)
2.必须要同时 重写equals()和HashCode(); 才能有效“唯一性”
3、当覆盖了equals方法时,比较对象是否相等将通过覆盖后的equals方法进行比较(判断对象的内容是否相等)。
4、将对象放入到集合中时,首先判断要放入对象的hashcode值与集合中的任意一个元素的hashcode值是否相等,如果不相等直接将该对象放入集合中。如果hashcode值相等,然后再通过equals方法判断要放入对象与集合中的任意一个对象是否相等,如果equals判断不相等,直接将该元素放入到集合中,否则不放入。
5.流程图:
.
package demo;
public class Person {
private String name;
private String sex;
public Person(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@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 (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
}
package demo;
import java.util.HashSet;
import java.util.Set;
public class PersonDemo {
public void demo() {
Person person=new Person("张三","男");
Person person1=new Person("张三","男");
Person person2=new Person("李四","女");
Set<Person> set=new HashSet<Person>();
System.out.println("person==person1:"+(person==person1));
System.out.println("person.equals(person1):"+person.equals(person1));
System.out.println("person.hashCode():"+person.hashCode());
System.out.println("person1.hashCode():"+person1.hashCode());
set.add(person);
set.add(person1);
System.out.println("加入后:person.hashCode():"+person.hashCode());
System.out.println("加入后:person1.hashCode():"+person1.hashCode());
System.out.println(set.size());
System.out.println(set.hashCode());
set.add(person2);
System.out.println(set.size());
System.out.println(set.hashCode());
}
public static void main(String[] args) {
new PersonDemo().demo();;
}
}
运算结果:
person==person1:false
person.equals(person1):true
person.hashCode():24052527
person1.hashCode():24052527
加入后:person.hashCode():24052527
加入后:person1.hashCode():24052527
1
24052527
2
50180278
以下两个链接为:更为详细注解
1:https://blog.csdn.net/bailu666666/article/details/81153815