文章目录
一、Set集合
Set 接口 集 : 数据是唯一存储,无序的。
HashSet实现类:
底层 数据结构 哈希表。
1.HashSet
数组 + 链表 + 二叉树。
原理:
原码:
/*
* new HashSet:
* 加载因子:
* static final float DEFAULT_LOAD_FACTOR = 0.75f;
*
* 数组的初始容量: 16
* static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
* 二叉树节点临界值:
* static final int TREEIFY_THRESHOLD = 8;
*
*/
HashSet<String> set = new HashSet<>();
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
}
}
Set<String> set = new HashSet<>();
set.add("ab");
set.add("ac");
set.add("ba");
System.out.println(set);// [ab, ac, ba]
set.add("ab");
System.out.println(set);// [ab, ac, ba]
重写:hashCode和equals()方法:
class Student{
private int no;
private String name;
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student [no=" + no + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + no;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)// guojing.equals(guojing)
return true;
if (obj == null)// guojing.equals(null)
return false;
if (this.getClass() != obj.getClass())// guojing.equals("hello")
return false;
Student other = (Student) obj;//
if (no != other.no)
return false;
return true;
}
/* @Override
public int hashCode() {
return no;
}
@Override
public boolean equals(Object obj) {
// 只要学号相同 那么 就返回 true
// this.no (Student)obj .no
Student stu = (Student)obj;//
return this.no == stu.no;
}*/
}
public class TestHashSet1 {
public static void main(String[] args) {
Set<Student> set = new HashSet<>();
Student guojing = new Student(11, "郭靖");
Student yangkang = new Student(11, "郭靖");
Student huangrong = new Student(22, "黄蓉");
set.add(guojing);
set.add(yangkang);
set.add(huangrong);
//信息
set.forEach(System.out::println);
}
}
2、TreeSet
基本应用:
public static void main(String[] args) {
// 默认: 自然升序排序 Comparable
// Set<String> set = new TreeSet<>();
// Comparator
Set<String> set = new TreeSet<>((s1,s2)->s2.compareTo(s1));
set.add("aa");
set.add("cc");
set.add("bb");
// System.out.println(set);// [aa, bb, cc]
System.out.println(set);// [cc, bb, aa]
版权声明:本文为weixin_45505750原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。