黑马程序员技术交流社区
标题:
练习:往HashSet放入不重复自定义对象
[打印本页]
作者:
Synaric
时间:
2015-10-7 11:14
标题:
练习:往HashSet放入不重复自定义对象
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
/*
* 需求:往HashSet中存入自定义的Person对象
* Person包含两个域:姓名和年龄
* 姓名、年龄均相同的Person是一个对象
* 要求HashSet中不存在相同的Person
* 思路:1、定义Person类存储字段
* 2、创建HashSet集合保存Person对象
* 3、重写Person的hashCode方法和wquals方法
*/
class Person{
private String name;
private int age;
Person(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
//重写hashCode方法
@Override
public int hashCode() {
return (name == null ? "".hashCode() : name.hashCode()) + age;
}
//重写equals方法
//我们的判断准则是name和age
//也就是说,两个对象a和b,即使引用不同,也判定相等
@Override
public boolean equals(Object obj) {
//快速排除非Person类型和null
if(!(obj instanceof Person))
return false;
//强制转换
Person p = (Person)obj;
//千万别写this.name.equals(p.name)
//因为不保证this.name不为null(即使这里没有set方法,可以通过反射更改为null)
return Objects.equals(name, p.name) && Objects.equals(age, p.age);
}
@Override
public String toString() {
return "Person[name: " + name + " age: " + age + "]";
}
}
public class HashSetDemo {
public static void main(String[] args) {
//创建HashSet
HashSet<Person> hashSet = new HashSet<Person>();
hashSet.add( new Person("A", 17));
hashSet.add( new Person("B", 18));
hashSet.add( new Person(null, 17));
hashSet.add( new Person("B", 18));
hashSet.add( new Person("C", 23));
hashSet.add( new Person(null, 17));
//遍历元素并打印
for(Iterator<Person> it = hashSet.iterator();it.hasNext();){
System.out.println(it.next());
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2