一、Set集合概述和特点
Set集合的特点:
元素存储无序
没有索引,只能通过迭代器或增强for循环遍历
不能存储重复元素
Set集合的基本使用:
public class SetDemo { 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); } } }
二、哈希值
哈希值简介
是JDK根据对象的地址或者字符串或者数字算出来的int类型的
如何获取哈希值
Object类的public int hashCode():返回对象的哈希值
哈希值的特点
同一个对象多次调用hashCode()方法返回哈希值是相同的
默认情况下,不同对象的哈希值是不同的,而重写hashCode(),可以实现让不同对象的哈希值相同
获取哈希值的代码:
学生类
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; } }
测试类
public class HashDemo { public static void main(String[] args) { //创建学生对象 Student s1 = new Student("小明",20); //同一个对象多次调用hashCode()方法返回的哈希值是相同的 System.out.println(s1.hashCode()); //1060830840 System.out.println(s1.hashCode()); //1060830840 System.out.println("--------"); Student s2 = new Student("林青霞",30); //默认情况下,不同对象的哈希值是不相同的 //通过方法重写,可以实现不同对象的哈希值是相同的 System.out.println(s2.hashCode()); //2137211482 System.out.println("--------"); System.out.println("hello".hashCode()); //99162322 System.out.println("world".hashCode()); //113318802 System.out.println("java".hashCode()); //3254818 System.out.println("world".hashCode()); //113318802 System.out.println("--------"); System.out.println("重地".hashCode()); //1179395 System.out.println("通话".hashCode()); //1179395 } }
三、HashSet集合的概述和特点
HashSet集合的特点:
● 底层数据结构的是哈希表
● 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致
● 没有带索引的方法,所以不能使用普通的for循环遍历
● 由于是Set集合,所以是不包含重复元素的集合
HashSet集合的基本使用:
public class HashSetDemo01 { public static void main(String[] args) { //创建集合对象 HashSet<String> hs = new HashSet<String>(); //添加元素 hs.add("hello"); hs.add("world"); hs.add("java"); hs.add("world"); //遍历 for(String s : hs) { System.out.println(s); } } }
HashSet集合保证元素唯一性的原理
1、根据对象的哈希值计算存储位置
如果当前位置没有元素,则直接存入
如果当前位置元素存在,则进入第二步
2、当前元素的元素和已经存在的元素比较哈希值
如果哈希值不同,则将当前元素进行存储
如果哈希值相同,则进入第三步
3、通过equals()方法比较两个元素的内容
如果内容不相同,则将当前元素进行存储
如果内容相同,则步存储当前元素
四、LinkedHashSet集合概述和特点
LinkedHashSet集合特点:
● 哈希表和链表实现的Set接口,具有可预测的迭代次序
● 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
● 由哈希表保证元素唯一,也就是说没有重复的元素
LinkedHashSet集合基本使用
public class LinkedHashSetDemo { public static void main(String[] args) { //创建集合对象 LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>(); //添加元素 linkedHashSet.add("hello"); linkedHashSet.add("world"); linkedHashSet.add("java"); linkedHashSet.add("world"); //遍历集合 for(String s : linkedHashSet) { System.out.println(s); } } }