java集合学习
Set集合
特点:无序唯一
需要注意的是去重需要重写Student的equals和hashcode方法
package test5;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
单列集合
SET集合
无序不可重复的
* */
public class test {
public static void main(String[] args) {
//1.创建集合对象
Set<Student> set=new HashSet<>();
//2.创建元素对象
Student s1=new Student("吴迪",12);
Student s2=new Student("张三",13);
Student s3=new Student("李四",11);
Student s4=new Student("王五",14);
Student s5=new Student("张三",13);
//3.添加学生元素
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
//4.遍历集合
/*
去重
Set集合保证元素唯一性是依赖equals和hashcode两个方法
Student没有重写这两个方法所以默认调用的是object类的
而object类的equals默认的是比较地址的值
解决方法:
重写Student的equals和hashcode方法
*/
Iterator<Student> iterator = set.iterator();
while (iterator.hasNext()){
Student s= iterator.next();
System.out.println(s);
}
System.out.println("----分割----");
//foreach遍历
for (Student s:set) {
System.out.println(s);
}
}
}
package test5;
import java.util.Objects;
//学生类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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 boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}