Thinking in Java: deep research on Containers
In terms of programming style, the hashCode () method should always be overwritten when the equals method is overwritten.
3. If an object is used in any sort containers, such as SortedSet (TreeSet is its unique implementation), it must implement the Comparable interface.
PS: In the interface implementation method compareTo (), should not use the form of return i-i2, error programming, because this does not take into account the i-i2 value overflow problem, should
Return (arg. I <I? -1: (arg. I = I? 0: 1 ))
4 if the elements in the HashSet container do not redefine hashCode (), placing them in any hash implementation may produce duplicate values, which may not even produce runtime errors. The only reliable method is to write a single test.
5. SortedSet means "sorting elements by object comparison functions", rather than "element insertion order ".
6. the sorting order of priority queue elements is also controlled by Comparable.
Understanding Map:
1: HashMap: implemented based on the hash list. You can use the constructor to set the capacity and load factor to adjust the container performance.
2: LinkedHashMap: It is different from HashMap in iteration time. The order of key-value pairs obtained is the insertion order or LRU order. Except for iterative access, the performance is slower.
3: TreeMap: Based on the implementation of the Red and black trees. When you view "keys" or "key-value pairs", they are sorted (by Comparable method). The unique Map with subMap () method can return a subtree.
4: WeakHashMap: weak key ing, which allows you to release the objects to which the ing is directed. If no reference points to a "key" outside the ing, this key can be recycled by the garbage collector.
5: IdentityHashMap: Use = instead of equals () to compare the hash ing of the "key"
PS: any key must have an equals method. If the key is used for hash Map, an appropriate hashCode method must be provided. If the key is used for TreeMap, Comparable must be implemented.
7. The result of the values method can be printed directly in the map. This method will generate a Collection containing all the values in the Map,Because these collections are supported by Map, any changes to the Collection will be reflected in the associated Map.
8. LinkedHashMap hashes all elements, but when traversing key-value pairs, it returns the key-value pairs in the insert order of the elements. In addition,You can set LinkedHashMap In the constructor to use the access-based LRU algorithm. Therefore, elements that have not been accessed will appear before the queue. This feature makes it easy for programs that regularly clean up elements to save space.
Hash and hash code:
1. The hashCode () method of the Object generates the hash code, which is calculated using the Object address by default.
2. You may think that you only need to write the override version of the appropriate hashCode () method. But it still cannot run normally, unless you overwrite the equals () method at the same time, it is also part of the Object.HashMap uses equals () to determine whether the current key is the same as the existing key in the table.
PS: The correct equals () method must meet the following five conditions:
1) Self-inverse: x. equals (x) must return true
2) symmetry: x. equals (y) returns true if and only when y. equals (x)
3) transmission: x. equals (y) and y. equals (z), x. equals (z) is true.
4) Consistency: If x. equals (y) returns true, x is not changed. If y is called multiple times, x. equals (y) returns true.
5) for any non-null reference value x, x. equals (null) must return false.
Hash for speed:
1. Because the bottleneck lies in the key query speed, one solution is to keep the key sorting status and then use Collections. BinarySearch ()
2. the hash goes further. It stores the key somewhere so that it can be quickly found. The fastest data structure for storing a group of elements is an array, so it is used to represent key information. The information is the hash code.
3. Usually, the conflict is handled by external links, and the array is saved directly to. Instead, the list is saved and the values in the list are linearly queried using the equals method.
4. Come in. Java hash functions all use the integer power of 2. For modern processors, division and remainder are the slowest operations. Use a hash of the integer power of 2 to replace division with a mask. Because get is the most commonly used operation, the % operation of the remainder is the most overhead, but the overhead can be eliminated by the integer power of 2.
9.When designing hashCode (), the most important factor is: Whenever hashCode () is called for the same object, the same value should be generated.. If your hashCode () method depends on variable data in the object, you should be careful. At the same time,HashCode () should not be dependent on unique object information, especially the value of this., This can only generate a very bad hashCode () because it cannot generate a new key so that it is the same as the key in the original key-Value Pair in put.
10. To use hashCode, it must be fast and meaningful, that is, it mustGenerate hash code based on object content. Hash Codes do not have to be unique. However, through hashCode () and equals, you must be able to fully identify the object.
Performance:
1. Avoid using Vector (the only reason for normal operation is to forward compatibility and be adapted to List)
2TreeSet iteration is usually faster than HashSet. In addition, for insert operations, HashSet is more expensive than HashSet, which is caused by additional overhead caused by maintaining the linked list.
3. The performance of Hashtable is roughly the same as that of HashMap. Because HashMap is used to replace Hashtable. Therefore, they use the same underlying storage and search mechanism.
4. IdentityHashMap has completely different performance because it uses = instead of equals to compare elements.
Performance factors of HashMap:
Capacity: number of bits in the table (slot)
Initial Capacity: The number of BITs owned by the table during creation. Both HashMap and HashSet have constructors that allow you to only have initial capacity.
Size: the number of items currently stored in the table.
Load Factor: Size/capacity. Both HashMap and HashSet have constructors that allow you to specify the load factor, indicating that the container will automatically add its capacity (number of BITs) when the load condition reaches the threshold ), the implementation method is to roughly double the capacity and re-distribute existing objects to the new bucket bits (this is called rehash)
Synchronization Control of Collection or Map:
1. The Collections class can automatically synchronize the entire container. Its syntax is similar to "unmodified.
List a = Collections. synchronizedList (new ArrayList (data ));
It is better to pass the newly generated container directly to the appropriate "synchronization" method as shown above, so there will be no chance of leaking out of the non-synchronous version.
Quick error:
Java containers have a protection mechanism to prevent multiple processes from simultaneously modifying the content of the same container. Java container class libraries adopt the fail fast mechanism. It detects all changes on the container except the operations performed by your processes. Once other processes change the container, it immediately throws a ConcurrentModificationException. For example, after the container obtains the iterator, something is put into the container.
ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteArraySet all use techniques that can avoid ConcurrentModificationException.
Hold reference:
1. the java. lang. ref class library contains a group of classes. These classes are particularly useful when there are large objects that may exhaust the memory. SoftReference, WeakReference, and PhantomReference are supported.When the objects being investigated in the garbage collection period can only be "available" through a Reference object, these different Derived classes provide different levels of indirect indication for the garbage collector.
2. If you want to continue to hold a Reference to an object and want to access it later, but want to allow the Garbage Collector to release it, you should use the Reference object. In this way, you can continue to use the object and allow the object to be released when the memory is exhausted.
3. Use the Reference object as the medium (proxy) between you and the normal Reference. In addition, there must be no normal Reference pointing to that object, so that the above purpose can be achieved.
4. For the differences and functions of SoftReference, WeakReference, and PhantomReference, see JVM.
5. When SoftReference and WeakReference are used,You can choose whether to put them in ReferenceQueue (used as a tool for "cleaning before recycling", see JVM). PhantomReference can only rely on ReferenceQueue.
6. WeakHashMap: see JVM. It is used to save WeakReference. In this ing, each value only saves one instance to save storage space, and WeakHashMap allows the Garbage Collector to automatically clean up keys and values, so it is very convenient.
Java 1.0/1.1 containers (learn more ):
1. Enmuberation: the interface of an earlier version of the Iterator is smaller than that of Iterator, but Iterator should be used whenever possible in code. You can use the Collections. enumeration () method to generate an Enumeration from the Collection.
2. Hashtable: As mentioned above, the basic Hashtable is similar to HashMap. Use HashMap whenever possible (there are still many other options for multi-thread synchronization)
3. BisSet: If you want to efficiently store a large amount of "On/Off" information, BitSet is a good choice. However, its efficiency is only for space. If efficient access time is required, BitSet is a little slower than the local array, and the minimum BitSet capacity is Long: 64 bits. If the storage content is small, for example, BitSet wastes some space. BitSet will also expand its capacity with the addition of elements like normal containers.In general, if you have a set of identifiers that can be named, EnumSet is usually a better choice.Because EnumSet allows you to operate based on the name rather than the digit location, you can reduce errors.