public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Student> hashMap = new HashMap<>();
hashMap.put("001",new Student(1,"张三",12));
hashMap.put("002",new Student(2,"张三1",14));
hashMap.put("003",new Student(3,"张三2",11));
hashMap.put("004",new Student(4,"张三3",17));
//遍历KeySet,获取HashMap中的key
Set<String> strings = hashMap.keySet();
for (String k : strings){
System.out.println(k+":"+hashMap.get(k).getName());
}
//使用返回Collection集合
Collection<Student> values = hashMap.values();
for (Student s : values){
System.out.println(s);
}
//使用entrySet()
Set<Map.Entry<String, Student>> entries = hashMap.entrySet();
for (Map.Entry<String, Student> e : entries){
System.out.println(e.getKey());
System.out.println(e.getValue());
}
//使用迭代器,使用迭代器接口Iterator 接口
Iterator<Student> iterator = hashMap.values().iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//获取键值,取得内容
Iterator<String> iterator1 = hashMap.keySet().iterator();
while (iterator1.hasNext()){
String key = iterator1.next();
System.out.println(hashMap.get(key));
}
}
}
HashMap是非线程安全,Hashtable是线程安全的,如果在单线程main线程程序中,使用了
线程安全的工具类,效率就低,根据使用量上来说还是HashMap使用的多。
集合接口及工具类总结:
Collection 接口
List 接口
ArrayList 动态数组,有序 插入删除速度慢,读取速度
LinkedList 双向链表,插入删除速度快,读取速度慢
Vector 动态数组,线程安全
Set 接口
HashSet 唯一集合,无序
TreeSet 唯一集合,是有序
Map 接口
HashMap K,V键值对集合,双列集合
TreeMap 根据key有序的map集合
Hashtable 和 HashMap一样,双列集合,线程安全