刚才看帖子发现有个人说了下他的面试,其中有一段是关于HashMap的
问:HashMap是有序的么,回答无序,回答有序的同学请点下面
=======相关链接======
手写hashmap请点击雷霆崖传送门
问:那有没有有序的map,回答treemap和linkedhashmap
这里引出了这个问题,为什么这两个可以有序,我先给出一段网上随处可见的他们三者的区别
1.HashMap里面存入的键值对在取出的时候是随机的,也是我们最常用的一个Map.它根据键的HashCode值存储数据,根据键可以直接获取它的值,具有很快的访问速度。在Map 中插入、删除和定位元素,HashMap 是最好的选择
2.TreeMap取出来的是排序后的键值对。但如果您要按自然顺序或自定义顺序遍历键,那么TreeMap会更好
3. LinkedHashMap 是HashMap的一个子类,如果需要输出的顺序和输入的相同,那么用LinkedHashMap可以实现
这么回答没问题,接下来会问他们是怎么实现的有序,这里可以通过数据结构想一下,tree的中序遍历是有序的,是不是treemap的迭代使用的中序遍历,并且是自然顺序,而链表是一个链一个的,所以输出的顺序是插入的顺序,这些就不得而知了,经过证实treemap里的entry是一颗红黑树,红黑树也是一颗平衡二叉树,比二叉树多了左旋,右旋以及反转这三个平衡方法
对于二叉树的了解可以点一下链接
=====相关链接=====
手写二叉树暴风城传送门
下面给出几段小代码,大家可以尝试下
public class Test{
public static void main(String[] args) {
try {
useHashMap();
System.out.println();
useTreeMap();
System.out.println();
useLikedHashMap();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void useHashMap() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Level 1");
map.put("2", "Level 2");
map.put("3", "Level 3");
map.put("a", "Level a");
map.put("c", "Level c");
map.put("b", "Level b");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
public static void useTreeMap() throws Exception {
Map<String, String> map = new TreeMap<String, String>();
map.put("1", "Level 1");
map.put("3", "Level 3");
map.put("2", "Level 2");
map.put("a", "Level a");
map.put("c", "Level c");
map.put("b", "Level b");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
public static void useLikedHashMap() throws Exception {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("1", "Level 1");
map.put("2", "Level 2");
map.put("3", "Level 3");
map.put("a", "Level a");
map.put("c", "Level c");
map.put("b", "Level b");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue());
}
}
}