类集
(1)ArrayList Vctor LinkedList
ArrayList Vctor LinkedList
(2)fail-fast与fail-safe
1.出现同步修改 当一个或多个线程遍历一个集合 此时另一个线程修改内容出现并发修改
2.Fail-fast机制
fail-fast遍历一个集合时当结构被修改抛出Concurrent Modification Exception
A.单线程环境 集合被创建在遍历过程中修改结构
B.多线程环境 一个线程遍历一个线程修改
3.Fail-fast如何检测
迭代器遍历过程中直接访问内部数据,为了保证遍历过程中不被修改,迭代器内部为元素添加modeCount标记 当执行hashNext()/next()遍历下一个元素之前都会检测modeCount变量是否等于expectedmodeCount 相等遍历不相等抛出异常终止遍历
4.java.util包下的集合类都是快速失败的,不能在多线程下发生并发修改(迭代过程中被修改)
5.Fail-safe机制
在遍历时 拷贝原有集合元素 遍历拷贝集合
遍历拷贝集合所以在进行迭代器检测时不能检测到
java.util.concurrent包下的容器都是安全失败
(3)Set与Map
(4)HashMap、TreeMap、Hashtable
1.HashMap特性
HashMap可以存入 null键和值,HashTable不能 hashMap线程不安全效率高,hastable线程安全效率低
2.HashMap工作原理,get方法工作原理
基于hashing(哈希法)原理实现。使用put存储到对象到hashmap中当我们使用put传递key和value时,使用get从hashmap中获取对象
A.先调用hashCode()方法 返回hashCode用于找到bucket位置来存储一个或者多个Entry对象(key,value,next)
B.HashMap实在bucket中存储key和value作为Map.Entry
3.当两个对象hashCode相同是发生什么
存放:HashCode相同 所以bucket位置相同 会发生碰撞 HashMap使用链表存储所以Entry存储到链表中
获取:找到bucket为重 调用keys.equals发放去找链表正确的节点 最终找到值
4.如果hashMap大小超过负载因子
默认负载因子 大小0.75 当一个map填满75%时 会自动库容原来大小两倍bucket数组,来重新调整map大熊 并将原来对象放入新的bucket数组中 整个过程rehashing
HashMap源码实现(参考https://blog.csdn.net/danielzhou888/article/details/84332201)
package main;
public class CustomHashMap<K,V> {
private class Entry<K,V>{
int hash;
K key;
V value;
Entry<K,V> next;
Entry(int hash,K key,V value,Entry<K,V> next){
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
private static final int DEFAULT_CAPATITY = 1<<4;
private Entry<K,V>[] table;
private int capacity;
private int size;
public CustomHashMap(){
this(DEFAULT_CAPATITY);
}
public CustomHashMap(int capacity){
if(capacity<0){
throw new IllegalArgumentException();
}else{
table = new Entry[capacity];
size = 0;
this.capacity = capacity;
}
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0?true:false;
}
private int hash(K key){
double tmp = key.hashCode()*(Math.pow(5,0.5)-1)/2;
double digit = tmp - Math.floor(tmp);
return (int)Math.floor(digit*capacity);
}
public void put(K key,V value){
if(key == null){
throw new IllegalArgumentException();
}
int hash = hash(key);
Entry<K,V> nEntry = new Entry<K,V>(hash,key,value,null);
Entry<K,V> entry = table[hash];
while(entry!=null){
if(entry.key.equals(key)){
entry.value = value;
return ;
}
entry = entry.next;
}
nEntry.next = table[hash];
table[hash] = nEntry;
size++;
}
public V get(K key){
if(key == null){
throw new IllegalArgumentException();
}
int hash = hash(key);
Entry<K,V> entry = table[hash];
while(entry!=null){
if(entry.key.equals(key)){
return entry.value;
}
entry = entry.next;
}
return null;
}
public static void main(String[] args) {
CustomHashMap<String,String> map = new CustomHashMap<String,String>();
map.put("1","2");
map.put("1","22");
System.out.println(map.get("1"));
}
}