Hashtable class
Hashtable inherits the Map interface and implements a hash table with a key-value mapping. Any non-null object can be used as a key or value.
Use put(key, value) to add data, use get(key) to retrieve data. The time overhead of these two basic operations is constant.
Hashtable adjusts performance through the initial capacity and load factor parameters. Usually, the default load factor 0.75 can better achieve time and space balance. Increasing the load factor can save space but the corresponding search time will increase, which will affect operations like get and put.
A simple example of using a Hashtable is as follows: put 1, 2, and 3 into a Hashtable, and their keys are "one", "two", "three" respectively:
Hashtable numbers = new Hashtable();numbers.put("one", new Integer(1));numbers.put("two", new Integer(2));numbers.put("three", new Integer(3));To take out a number, such as 2, use the corresponding key:
Integer n = (Integer)numbers.get("two");System.out.println("two = " + n);Since an object as a key will determine the position of the corresponding value by calculating its hash function, any object as a key must implement the hashCode and equals methods. The hashCode and equals methods inherit from the root class Object. If you use a custom class as a key, be very careful. According to the definition of the hash function, if the two objects are the same, that is, obj1.equals(obj2)=true, their hashCode must be the same, but if the two objects are different, their hashCodes may not be different. If the hashCodes of two different objects are the same, this phenomenon is called conflict. Conflict will increase the time overhead of operating the hash table. Therefore, try to define the hashCode() method to speed up the operation of the hash table.
If the same object has different hashCodes, the operation on the hash table will have unexpected results (the expected get method returns null). To avoid this problem, you only need to remember one thing: you should rewrite the equals method and hashCode method at the same time, rather than just writing one of them.
Hashtable is synchronized.
HashMap class
HashMap is similar to Hashtable, the difference is that HashMap is asynchronous and allows null, i.e. null value and null key. However, when HashMap is regarded as a Collection (the values() method can return a Collection), its iterative suboperation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of iteration operations is very important, do not set the initialization capacity of HashMap to be too high or the load factor is too low.
Summarize