239 哈希值
240 HashSet集合概述和特点
(查看帮助文档)
class HashCode<E> implements Set<E>
该类实现Set接口,由HashMap哈希表支持,对集合的迭代(遍历)顺序不作任何保证,允许null元素。
【HashSet集合特点】
- 底层数据结构是哈希表
- 对集合的迭代(遍历)顺序不作任何保证,不保证存储和取出的元素顺序一致
- 没有带索引的方法,因此不能使用普通for循环遍历
- 是Set集合,Set集合都不包含重复元素
练习,存储字符串并遍历
--------------------------------------------------------------
package e240;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
hs.add("1240");
hs.add("2hello");
hs.add("3HashSet");
for (String s:hs){
System.out.println(s);
}
}
}
--------------------------------------------------------------
3HashSet
1240
2hello
241 HashSet集合保证元素唯一性
238不是说过这个了吗,略
242 常见数据结构之哈希表
- JDK8之前,采用数组+链表实现,是元素为链表的数组
- JDK8之后,在长度比较长的时候,底层实现了优化
默认数组容量为16,即0-15
元素的哈希值对16取余,余数多少就存到哪个索引里,有多个元素余数相同时,则比较元素的哈希值和值,相同则不存储,不相同则存储
package e239;
// 创建学生对象
// 依次验证
// 同一对象多次调用的哈希值相同,
// 不同对象的哈希值不同,
// 英文字符串的哈希值不同,汉字字符串的哈希值相同
public class HashDemo {
public static void main(String[] args) {
Student s1 = new Student("TRACY",33);
System.out.println("9.s1.HashCode:\n\t"+s1.hashCode());
System.out.println("10.s1.HashCode:\n\t"+s1.hashCode());
Student s2 = new Student("JIMMY",22);
System.out.println("15.s2.hashCode\n\t"+s2.hashCode());
System.out.println("17.hello.hashCode\n\t"+"hello".hashCode());
System.out.println("18.hello.hashCode\n\t"+"hello".hashCode());
System.out.println("19.java.hashCode\n\t"+"java".hashCode());
System.out.println("21.九月.hashCode\n\t"+"九月".hashCode());
System.out.println("22.二十八.hashCode\n\t"+"二十八".hashCode());
}
}
//9.s1.HashCode:
// 460141958
//10.s1.HashCode:
// 460141958
//15.s2.hashCode
// 1163157884
//17.hello.hashCode
// 99162322
//18.hello.hashCode
// 99162322
//19.java.hashCode
// 3254818
//21.九月.hashCode
// 27873261
//22.二十八.hashCode
// 814569553