LinkedHashMap集合
我们知道HashMap保证成对元素唯一,并且查询速度很快,可是成对元素存放进去是没有顺序的,那么我们要保证有序,还要速度快怎么办呢?
在HashMap下面有一个子类LinkedHashMap,它是链表和哈希表组合的一个数据存储结构。
java.util.LinkedHashMap<K,V>entends HashMap<K,V>
Map接口的哈希表和链接列表实现,具有可预的迭代顺序。
底层原理:
哈希表+链表(记录元素的顺序)
public static void main(String[] args) {
HashMap<String,String>map = new HashMap<>();
map.put("a","a");
map.put("c","c");
map.put("b", "b");
map.put("a" , "d");
System.out.println(map);
LinkedHashMap<String,String> linked = new LinkedHashMap<>( );
linked .put("a" , "a" ) ;
linked.put( "c" , "c");
linked.put("b","b");
linked.put("a" ,"b");
System.out.println(linked);
}
package hashlinkedmap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class Deno1 {
public static void main(String[] args) {
//创建Map集合
Map map = new LinkedHashMap<>();
map.put("1", "网易云");
map.put("2", "qq");
map.put("3", "cc");
//获取所有键
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
System.out.println("键:" + key + '/t' + "值:"+ value);
}
}
}
Hashtable集合
java.util.Hashtable<K,V>集合implements Map<K,V>接口
Hashtable:底层也是一个哈希表,是一个线程安全的集合,是单线程集合,速度慢
HashNap:底层是一个哈希表,是一个线程不安全的集合,是多线程的集合,速度快
HashMap集合(之前学的所有的集合):可以存储null值, nulL键
Hashtable集合,不能存储null值,nut键
HashtabLe和vector集合一样,在jdk1.2版本之后被更先进的集合(HashMap, ArrayList)取代了
Hashtable的子类Properties依然活跃在历史舞台
Properties集合是一个唯—和I0流相结合的集合
HashMap<String, String> map = new HashMap<>();
map.put(null, "a");
map.put("b", null);
map.put(null, null);
System.out.println(map);
Hashtable<String, String> table = new Hashtable<>();
//table.put(nuLl, "a");//NuLlPointerException
//table.put( "b" , null); //NulLPointerException
table.put(null, null); //NuLLPointerException
public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("奥迪", 380000);
hashtable.put("大众", 180000);
hashtable.put("奔驰", 450000);
hashtable.put("宝马", 500000);
hashtable.put("凯迪拉克", 430000);
//遍历方法一:entrySet
System.out.println("————————entrySet方式遍历————————");
Set<Map.Entry<String, Integer>> entrySet = hashtable.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey()+"/t"+entry.getValue());
}
//键值相同则替代value,并返回原来的Value
hashtable.put("奥迪", 350000);
//存入键相同的键值对相当于替换
hashtable.replace("大众", 300000);
hashtable.replace("奔驰", 450000, 480000);//使用新值替换老值
//存储键和值都是null值的元素
//删除
hashtable.remove("凯迪拉克");//直接通过键来删除映射关系
hashtable.remove("宝马", 500000);//通过完整的键值对删除映射关系
//遍历方法二:KeySet
System.out.println("————————KeySet方式遍历————————");
Set<String> keySet = hashtable.keySet();
for (String key : keySet) {
System.out.println(key+"/t"+hashtable.get(key));
}
}
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/271743.html