package com.itheima2;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 使用hashSet创建的集合数据可以重复
// 使用set创建的集合数据可以重复
// **把**操作的对象类重写eqauls方法 和重写hashCode方法则可以去重****
// 创建集合对象
HashSet hs = new HashSet();
// 创建学生对象
Student s = new Student("宋东雄", 12);
Student s1 = new Student("宋东辉", 126);
Student s2 = new Student("宋东辉", 126);
// 添加元素对象
hs.add(s1);
hs.add(s);
hs.add(s2);
// foreach遍历元素
for (Student object : hs) {
System.out.println(object.getName() + " " + object.getAge());
}
System.out.println("-------------------------");
// 使用迭代器遍历元素
Iterator it = hs.iterator();
// it.hasNext()判断下一个是否为空
while (it.hasNext()) {
// it.next();获取下一个值
Student student = (Student) it.next();
System.out.println(student.getName() + " " + student.getAge());
}
// 把集合装换为数组
Object[] obj = hs.toArray();
// 使用for循环遍历
for (int i = 0; i < obj.length; i++) {
Student ss = (Student) obj[i];
System.out.println(ss);
}
}
}
class Student {
String name;
int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return age == other.age && Objects.equals(name, other.name);
}
}



