集合
前言
一、Collection常用方法
public interface Collection<E> extends Iterable<E> {
}
List<Integer> collection = new ArrayList<>();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
// 迭代器
Iterator<Integer> iterator = collection.iterator();
while (iterator.hasNext()) {
Integer v = iterator.next();
System.out.println(v);
}
//增强for循环
for (Integer i : collection) {
System.out.println(i);
}
二、冒泡排序 :
三、List的源码,知识点
(一)ArryList注意事项: 线程不安全,执行效率高,底层数组实现 ,默认10扩容再1.5倍扩容
transient Object[] elementData; //transient 瞬变,短暂的 不被序列化
// 没有加synchronized 线程不安全
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
(二)Vector 线程安全 ,方法基本带有synchronized 2倍扩容
(三)LinkedList 线程不安全,新增删除快,效率高,底层是链表。
(四)总结 ArryList 和 LinkedList 比较
(五)CopyOnWriteArrayList 线程安全 ReentrantLock
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
四、Set源码以及知识点 : 不能重复,可以添加null,取出的顺序不是添加的顺序,但是是固定的
@org.junit.Test
public void test03() {
HashSet set = new HashSet();
set.add("tom");//yes
set.add("tom");//no
set.add(new Dog("yellow"));//yes
set.add(new Dog("yellow"));//yes
set.add(new String("yellow"));//yes 重写了equls 内存地址相同
set.add(new String("yellow"));//no
System.out.println(set.toString());
//[Dog{name=yellow}, tom, Dog{name=yellow}, yellow]
}
(一)HashSet底层是 数组+单项链表+红黑树 可有null只有1个null
@org.junit.Test
public void test04() {
HashSet table = new HashSet();
table.add("java");
table.add("php");
table.add("java");
System.out.println(table.toString());
/*
1、执行 new HashSet()
public HashSet() {
map = new HashMap<>();
}
2、执行.add("java")
public boolean add(E e) {
return map.put(e, PRESENT)==null; //PRESENT = new Object()
}
3、map.put(e, PRESENT)==null; 会执行putVal() 得到一个hash值 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; //初始化辅助变量
//第一次初始化扩容 返回16个长度Node数组 扩容方法看后面 tab=Node[]
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 通过hash值 计算在tab数组中的索引值 i 第一次在(0-16)之间 ,判断这个数组在这个索引值的值是否是null
//p 链表的第一个节点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 例子第三次java 会进入这里 因为通过hash 计算出来的索引值相等
// 判断以第一个位置的 node对象的hash 和准备加入的hash 相等,并且 准备加入的key和对象中的key相等
// key.equals(k)可能是传入的对象,比较属性
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 {
//tab[i] 对应位置是链表 则比较后面的值是否和key相同,如果相同立马下一步
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//注意细节: TREEIFY_THRESHOLD=8 添加后判断时候达到8个节点 ,就调用 treeifyBin() 树化 (转为红黑树)
// final void treeifyBin(Node<K,V>[] tab, int hash) {
// int n, index; Node<K,V> e;
// if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
// resize();
******
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 如果相同 java -> JACK -> mary -> java 则直接退出
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 加入节点长度 > 临界值 则扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
*/
/*
扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 第一次到这里 向左偏移4位 1*2*2*2*2 = 16 = DEFAULT_INITIAL_CAPACITY
// newCap = DEFAULT_INITIAL_CAPACITY;
// DEFAULT_LOAD_FACTOR加载因子0.75*16 = 12
// newThr 扩容的临界值 12 数组放了12个就扩容,目的是防止到后面几个位置大量添加堵塞
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 返回16长度Node数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
*/
}
(二)LinkedHashSet底层结构是 数组+双向聊表
@org.junit.Test
public void test05() {
LinkedHashSet table = new LinkedHashSet();
//LinkedHashSet 加入元素与取出元素顺序一致
//LinkedHashSet 底层是LinkedHashMap(HashMap子类)
//LinkedHashSet 底层结构式 数组+双向聊表
// 第一次扩容数组16 HashMap$Node[] 底层是LinkedHashMap$Entry 节点类
table.add("java");
table.add("php");
table.add("java");
table.add(null);
table.add(null);
System.out.println(table.toString());
}
@org.junit.Test
public void test06() {
LinkedHashSet linkedHashMap = new LinkedHashSet<>();
linkedHashMap.add(new Dog("小花", "12"));
linkedHashMap.add(new Dog("小花", "12"));
linkedHashMap.add(new Dog("小花", "12"));
linkedHashMap.add(new Dog("小红", "12"));
linkedHashMap.add(new Dog("小黄", "12"));
linkedHashMap.add(null);
linkedHashMap.add(null);
linkedHashMap.add(null);
System.out.println(linkedHashMap.toString());
}
五、Map
(一)遍历map方式
@org.junit.Test
public void test08() {
Map<Long, Staff> longStaffMap = new HashMap<>();
longStaffMap.put(1L, new Staff("json", 1L, BigDecimal.valueOf(10000)));
longStaffMap.put(2L, new Staff("jock", 2L, BigDecimal.valueOf(4000)));
longStaffMap.put(3L, new Staff("mary", 3L, BigDecimal.valueOf(7000)));
longStaffMap.put(4L, new Staff("kangkang", 4L, BigDecimal.valueOf(9000)));
System.out.println(longStaffMap.toString());
Set<Map.Entry<Long, Staff>> s = longStaffMap.entrySet();
// 遍历方式一
for (Map.Entry<Long, Staff> key : s) {
System.out.println("key:" + key.getKey() + ",value:" + key.getValue());
}
System.out.println("---------------------------");
// 遍历方式二
Set<Long> ids = longStaffMap.keySet();
for (Long key : ids) {
System.out.println("key:" + key + ",value:" + longStaffMap.get(key));
}
System.out.println("---------------------------");
// 遍历方式三
Iterator iterator = s.iterator();
while (iterator.hasNext()) {
Map.Entry<Long, Staff> next = (Map.Entry<Long, Staff>) iterator.next();
System.out.println("key:" + next.getKey() + ",value:" + next.getValue());
}
System.out.println("---------------------------");
}
(二)HashMap线程不安全 key value可以为null值
(三)HashTable ConcurrentHashMap 线程安全
(参考)
@org.junit.Test
public void test09() {
Hashtable hashtable = new Hashtable<>();
hashtable.put(1L, new Staff("json", 1L, BigDecimal.valueOf(10000)));
hashtable.put(2L, new Staff("jock", 2L, BigDecimal.valueOf(4000)));
hashtable.put(3L, null);// java.lang.NullPointerException
hashtable.put(null, new Staff("jock", 2L, BigDecimal.valueOf(4000)));// java.lang.NullPointerException
System.out.println(hashtable);
/*
初始化大小 new Hashtable<>();
public Hashtable() {
this(11, 0.75f);
}
加载因子 0.75 临界值 11 * 0.15 = 8
2倍加1 扩容 11*2+1=21
*/
}