Map: key-value映射 ,通过泛型对象的equals方法判断是否重复,key重复则覆盖。
HashMap:核心为Node类,1.8之前为Entry
存储数据过程:核心为产生hash值,该值用来对应数组的存储位置,当同一位置的链表长度为8的时候就会生成红黑树。
取数据过程:
-
获取key,计算hashcode();,获取hash值。定位数组位置
-
对应位置的链表中挨个比较key,通过equals进行比较,知道返回true为止
-
返回equals比较为true的节点的value对象
-
两个内容相同的对象必须具有相等的hashcode()
扩容:
初始大小为16,扩容系数为0.75,到达这个倍数的时候,就会变为之前额两倍大小。
/**-
自定义HashMap
*/
public class LsdHashMap<K,V> {
Node2<K,V>[] table;//位桶数组
int size;
public LsdHashMap(){
table=new Node2[16];//长度一般定义为2的整数次幂
}
public void put(K key,V value){
Node2 newNode=new Node2();
newNode.hash=myHash(key.hashCode(),table.length);
newNode.key=key;
newNode.value=value;
newNode.next=null;Node2 temp=table[newNode.hash];
//正在遍历的最后一个元素
Node2 iterLast=null;
boolean keyRepeat=false;
if(temp==null){
table[newNode.hash]=newNode;
size++;
}else{
//对应位置不为空,遍历对应的列表
while(temp!=null){
//key如果重复则进行覆盖
if(temp.key.equals(key)){
keyRepeat=true;
temp.value=value;//知识覆盖value,其他值保持不变
break;
}else{
//如果key不重复,则将
iterLast=temp;
temp=temp.next;
}
}
if(!keyRepeat){
//如果未发生key重复
iterLast.next=newNode;
size++;
}
}
}
public V get(K key){
int hash=myHash(key.hashCode(),table.length);
V value=null;
if(table[hash]!=null){
Node2 temp=table[hash];
while(temp!=null){
if(temp.key.equals(key)){
value=(V)temp.value;
break;
}else{
temp=temp.next;
}
}
}
return value;
}
public int myHash(int x,int length){
return x&(length-1);
}@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("[");
for(int i=0;i<table.length;i++){
Node2 temp=table[i];
while(temp!=null){
sb.append(temp.key+":"+temp.value+",");
temp=temp.next;
}
}
sb.setCharAt(sb.length()-1,’]’);
return sb.toString();
}public static void main(String[] args) {
LsdHashMap<Integer,String> lh=new LsdHashMap<Integer, String>();
lh.put(10,“aa”);
lh.put(20,“bb”);
lh.put(30,“cc”);
lh.put(20,“lsd”);
lh.put(5,“k”);
lh.put(21,“kk”);
lh.put(37,“kkk”);
System.out.println(lh);
System.out.println(lh.get(5));
System.out.println(lh.get(20));
} -
}
TreeMap :
TreeMap 是一个有序的key-value集合,它是通过红黑树实现的。
TreeMap 继承于AbstractMap,所以它是一个Map,即一个key-value集合。
TreeMap 实现了NavigableMap接口,意味着它支持一系列的导航方法。比如返回有序的key集合。
TreeMap 实现了Cloneable接口,意味着它能被克隆。
TreeMap 实现了java.io.Serializable接口,意味着它支持序列化。
TreeMap基于红黑树(Red-Black tree)实现。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
TreeMap的基本操作 containsKey、get、put 和 remove 的时间复杂度是 log(n) 。
另外,TreeMap是非同步的。 它的iterator 方法返回的迭代器是fail-fastl的
TreeMap:
import java.util.HashMap;
import java.util.Map;
public class TestMap {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
//通过equals判断是否重复,重复就覆盖values
map.put(1,"two");
System.out.println(map.get(1));
System.out.println(map.size());
System.out.println(map);
Map<Integer,String> map1=new HashMap<Integer,String>();
map1.put(4,"one");
map.putAll(map1);
System.out.println(map);
Map map11=new HashMap();
map11.put(3,"three");
map11.put("11","three");
System.out.println(map11);
}
}