测试HashMap代码:
- import java.util.HashMap;
- import java.util.Map;
- public class Test {
- public static void main(String[] args) {
- Map<String, String> map = new HashMap<String, String>();
- map.put(String.valueOf(System.nanoTime()) + "a", "1");
- map.put(String.valueOf(System.currentTimeMillis()) + "a", "2");
- map.put(String.valueOf(System.currentTimeMillis()) + "a", "3");
- for (Map.Entry<String, String> entry : map.entrySet()) {
- System.out.printf(entry.getValue());
- }
- }
- }
如果对HashMap的原理有所了解的话应该会考虑到结果是不确定的,因为"1","2","3"三个串的顺序是无法确定的.
对于HashMap重点要掌握其存储数据的方式.HashMap内部有一个transient Entry[] table;这个数组是实际用来存储数据的.需要注意的是Entry是个链式结构,后面可以链接多个Entry.table数组在构造方法中初始化,默认大小是16.
加入数据通过put方法实现.put中首先对对象的hashCode()结果进行再hash等一些列处理,得到一个index,这个index就是此对象应该存储的位置,如果table[index]中已经存在了一个要加入的对象,或者和要加入的对象equals的对象,则用新对象替换原有的对象.如果不存在,则在此位置加入该对象( 放在链表的头上) .
hash处理的过程比较麻烦,这里把代码抽取出来测试了一下:
- public class Test {
- public static void main(String[] args) {
- String str1 = System.nanoTime() + "a";
- String str2 = System.nanoTime() + "a";
- String str3 = System.nanoTime() + "a";
- int i1 = str1.hashCode();
- int i2 = str2.hashCode();
- int i3 = str3.hashCode();
- int hash1 = hash(i1);
- int hash2 = hash(i2);
- int hash3 = hash(i3);
- int index1 = indexFor(hash1, 16);
- int index2 = indexFor(hash2, 16);
- int index3 = indexFor(hash3, 16);
- System.out.println(index1);
- System.out.println(index2);
- System.out.println(index3);
- }
- private static int hash(int h) {
- h += ~(h << 9);
- h ^= (h >>> 14);
- h += (h << 4);
- h ^= (h >>> 10);
- return h;
- }
- static int indexFor(int h, int length) {
- return h & (length - 1);
- }
- }
把上面的例子多跑几次看看结果,就知道第一个例子中的原理了.
ps:自己的语言表达能力越来越差了,不知道该怎么搞.