05.hashCode方法和equals方法的优化
2018-10-15 本文已影响0人
今天庹
hashCode方法优化:
- 如果让hashCode()方法返回一个固定值,那么每个新添加的元素都要调用equals(Object obj)方法比较,那么效率较低
- 只需要让不同属性的值的元素产生不同的哈希值,那么就可以不再调用equals方法比较提高效率
package com.itheima_02;
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.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 (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/* @Override
public boolean equals(Object obj) {
System.out.println("--------");
//提高效率
if(this == obj) {
return true;
}
//提高程序健壮性
if(this.getClass() != obj.getClass()) {
return false;
}
//向下转型
Person p = (Person)obj;
if(this.name.equals(p.name)) {
return false;
}
if(this.age != p.age) {
return false;
}
return true;
}*/
}
package com.itheima_02;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
//创建集合对象
HashSet<Person> hs = new HashSet<Person>();
//创建元素对象
Person p = new Person("zhangsan",18);
Person p2 = new Person("lisi",19);
Person p3 = new Person("lisi",19);
//添加元素对象
hs.add(p);
hs.add(p2);
hs.add(p3);
//遍历集合
for (Person person : hs) {
System.out.println(person);
}
}
}