In-depth research on containers, insufficient research

Source: Internet
Author: User
Tags coding standards comparable

In-depth research on containers, insufficient research

Generally:

The basic idea of a ing table (also called an associated array) is the key-value (pair) Association maintained by the ing table, so you can use the key to find the value.

The standard Java class library contains several Map implementations, including HashMap, TreeMap, LinkedHashMap, WeakHashMap, ConcurrentHashMap, and IdentityHashMap.

They all have the same basic interface Map, but their behavior characteristics are different, this is manifested in efficiency, key-Value Pair storage and presentation order, Object Storage cycle, and how the ing table works in a multi-threaded program to determine the "key" equivalent policy. The number of Map interface implementations should make you feel the importance of this tool.

You can gain a deeper understanding of Map, which helps you observe how associated arrays are created. The following is an extremely simple implementation.

class AssociativeArray<K,V> {private Object[][] pairs;private int index;public AssociativeArray(int length) {pairs = new Object[length][2];}public void put(K key, V value) {if (index >= pairs.length) {throw new ArrayIndexOutOfBoundsException();}pairs[index++] = new Object[]{key, value};}public V get(K key) {for (int i = 0; i < index; i ++) {if (key.equals(pairs[i][0])) {return (V) pairs[i][1];}}return null;}@Overridepublic String toString() {StringBuffer result = new StringBuffer();for (int i = 0; i < index; i++) {result.append(pairs[i][0].toString());result.append(":");result.append(pairs[i][1].toString());if (i < index - 1) {result.append("\n");}}return result.toString();}}

The above version is simple, lacks efficiency, and is not flexible due to its fixed size.

Performance:

Performance is an important issue in ing tables. When linear search is used in get (), the execution speed is quite slow, which is where HashMap improves the speed.

HashMap uses a special value calledHash codeTo replace the slow search of the key pair. Hash code is a unique int value used to represent an object. It is obtained by converting and searching certain information of the object.

HashCode ()Is the method in the root class Object, soAllJava objects can generate hash codes. HashMap uses the hashCode () of the object for fast query. This method canSignificantly improve performance.

Below is the basic Map implementation. The asterisk (*) on HashMap indicates that if there are no other restrictions, it should be your default choice because it optimizes the speed. Others emphasize other features, so they are not as fast as HashMap.

HashMap:

Implementation of Map Based on Hash (It replaces HashTable).Insert and queryKey-Value PairThe overhead is fixed.. You can use the constructorSet capacity and load factor,Adjust container Performance.

LinkedHashMap:

Similar to HashMap, but the iteration time is used to obtain the "key-Value Pair"The order is the insertion order., OrIs the least recently used (LRU) Order. It is only a little slower than HashMap; it is faster in iterative access because it usesInternal Order of linked list maintenance.

TreeMap:

Based on the implementation of the Red and black trees. When you view "keys" or "key-value pairs", they areSort(The order is determined by Comparable or Comparator.). TreeMap features that the obtainedThe results are sorted.. TreeMap is the only Map with subMap () method. It can return a subtree.

WeakHashMap:

The weak key (weak key) ing allows you to release the objects pointed to by the ing; this isSolve some special problemsDesigned. If a key is not referenced outside of the ing, the key can be recycled by the garbage collector.

ConcurrentHashMap:

A thread-safe Map that does not involve synchronization locks.

IdentityHashMap:

Use= Replace equals ()Compares the hash ing of keys. Designed to solve special problems.

Hash is the most common method for storing elements in ing.

The requirements for keys used in Map are the same as those for elements in Set. Any keyRequiredThere is an equals () method; if the keyUsedHash Map, it must also have the appropriate hashCode () method; if the keyUsed for TReeMap must implement Comparable.


SortedMap:

With SortedMap (the unique implementation of the TreeMap period at present), we can ensure thatThe key is sorted.. This gives it additional features provided by the following methods in the SortedMap interface:

 Comparator<? superK> comparator()
Returns the comparator for sorting the keys in this ing. If the ing uses the natural sequence of keysNull.
 Set<Map.Entry<K,V>> entrySet()
ReturnsSetView.
 K firstKey()
Returns the first (lowest) Key in the ing.
 SortedMap<K,V> headMap(K toKey)
Return some views of this ing, whose key value is strictly lessToKey.
 Set<K> keySet()
ReturnsSetView.
 K lastKey()
Returns the last (highest) Key in the ing.
 SortedMap<K,V> subMap(K fromKey,K toKey)
Returns some views of this ing, whose key value ranges fromFromKey(Including)ToKey(Not included ).
 SortedMap<K,V> tailMap(K fromKey)
Returns some views mapped with a key greater than or equalFromKey.
 Collection<V> values()
ReturnsCollectionView.

LindedHashMap:

To speed up, LinkedHashMap hashes all elements, but when traversing key-value pairs, it returns the key-value pairs (System. out. println () in the insert sequence of the elements ()).

In addition, you can set LinkedHashMap In the constructor to use the least recently used (LRU) algorithm based on access, so those that have not been accessed (which can be viewed as needing to be deleted) this function is easy to implement for programs that need to regularly clean up elements to save space.


Who can recommend a step that is more reasonable than learning basic java? What kind of books do I need?

My suggestions are as follows:
1: learning the C language first. Of course, this has an inevitable relationship with you to become a java, because only after learning the C language can you know the underlying things, such as the B + tree, Map, and linked list, pointers, recursion, and other basic things
2: If you don't want to learn C language, you can do it, but you won't be a very good master. You will only be limited to between elementary and intermediate levels. I suggest you study tan haoqiang's C language.
3: to learn Java, we recommend that you do not read books such as Object-oriented Thinking and core code at the beginning. You should first find the book at the beginning to ensure that you can understand and fully understand the above, in addition, you can start to despise the author's coding standards and very spam Code. At this time, you can learn "Object-oriented Thinking" and "java core technology".
4: after learning the above books, you can take a look at refactoring, Java coding art, and effictive Java. These books can greatly improve your Object-oriented thinking.
5: Now you can take a look at design patterns, fully understand the ideas contained in design patterns, and use them freely. To this point, java is no longer difficult for you, you can try to see the JDK kernel code.
6: Let's take a look at Spring in action to learn Aspect-Oriented Programming, and then look at the Spring kernel source code.
7: I believe that LZ is a rare expert.
8: if you are still interested in J2ee, you can start with Servlet, struts, jsf, jsp, webwork, ibatis, hibernate, with the above basic technologies, you can master them within half a year.
9: Finally, I would like to give the landlord a loyal suggestion: Everything is inseparable from the foundation. Even if some people feel that they are not good enough, they can only position themselves at a certain level, the tall building begins with a brick
10: I believe you will succeed! Because you are already on the road, leaving a post to ask questions is a good proof that the landlord is more motivated. Come on !!!

Error Message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.