HashSet的练习
package com.hspedu;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
/**
* @author: guorui fu
* @versiion: 1.0
*/
public class HashSetExercise {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("小红",20));
hashSet.add(new Employee("刚子",25));
hashSet.add(new Employee("小红",20));
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()) {
Object employee = iterator.next();
System.out.println(employee);
}
}
}
class Employee{
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age &&
Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return
"name=" + name + '\'' +
"age=" + age;
}
}