目录
思维导图
1 Set集合
1.1 Set集合的概述和特点
Set集合特点
● 不包含重复元素的集合
● 没有带索引的方法,所以不能使用普通for循环遍历
Set集合练习
● 存储字符串并遍历
补充:
HashSet:对集合的迭代顺序不做任何保证
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("hello");
set.add("world");
set.add("java");
set.add("world");
for (String s:set){
System.out.println(s);
}
}
}
运行结果:
说明:因为Set集合是不包含重复元素的集合,所以即使添加了两次world,控制台依旧只输出一次
1.2 哈希值
哈希值:是JDK根据对象的地址或者字符串或者数字来算出来的int类型的数值
Object类中有一个方法可以获取对象的哈值
● public int hashCode():返回对象的哈希码值
注意:
同一个对象多次调用hashCode()方法返回的哈希值是相同的
默认情况下,不同对象的哈希值是不相同的
通过方法重写,可以实现不同对象的哈希值是相同的
1.3 HashSet集合概述和特点
HashSet集合特点
● 底层数据结构是哈希表
● 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
● 没有带索引的方法,所以不能使用普通for循环遍历
● 由于是Set集合,所以是不包含重复元素的集合
HashSet集合练习:
● 存储字符串并遍历
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("hello");
set.add("world");
set.add("java");
set.add("world");
for (String s:set){
System.out.println(s);
}
}
}
1.4 HashSet集合保证元素唯一性源码分析
HashSet集合添加一个元素的过程:
HashSet集合存储元素:
● 要保证元素的唯一性,需要重写hasCode()和equals()
1.5 常见数据结构之哈希表
哈希表:
● JDK8之前,底层采用数组+链表实现,可以说是一个元素链表的数组
● JDK8以后,在长度比较长的时候,底层实现了优化
案例:HashSet集合存储学生对象并遍历
示例代码:
//学生类
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 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);
}
}
//测试类
public class Test {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
Student s1 = new Student("jack", 10);
Student s2 = new Student("mary", 11);
Student s3 = new Student("jane", 13);
Student s4 = new Student("jane", 13);
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
for (Student s : hs){
System.out.println(s.getName() + "," + s.getAge());
}
}
}
1.6 LinkedHashSet集合概述和特点
LinkedHashSet集合特点
● 哈希表和链表实现的Set接口,具有可预测的迭代次序
● 由链表保证元素有序,也就是说元素