Java Collection: Overall structure

Source: Internet
Author: User

One, the collection in Java

The collection classes in Java are the most frequently used and most convenient classes in Java programming. The collection class can store any type of data as a container class, and of course it can also be combined with generics to store the specified type (although generics are only valid at compile time and run-time is erased). The collection class stores only references to objects and does not store the object itself. The capacity of a collection class can be dynamically extended during run time, and it also provides many convenient methods, such as the set, intersection, and so on.

Ii. set-Class structure

A collection in Java contains a variety of data structures, such as linked lists, queues, hash tables, and so on. From the inheritance structure of the class, it can be divided into two categories, one is inherited from the collection interface, and this kind of collection contains list, set and queue and other collection classes. The other is inherited from the map interface, which mainly contains the hash table related collection classes. Let's take a look at the inheritance structure of these two categories:

1. List, set, and queue

The green dashed line in the figure represents the implementation, the green solid lines represent the inheritance between the interfaces, and the blue solid lines represent the inheritance between the classes.

(1) List: We use more lists including ArrayList and LinkedList, the difference between the two is also obvious, from its name can be seen. The bottom of the ArrayList is implemented by the array, so its random access speed is relatively fast, but for the need for frequent additions and deletions, the efficiency is relatively low. For LinkedList, the underlying is implemented by linked lists, so adding and deleting operations is easier to complete, but less efficient for random access.

Let's look at the insertion efficiency of both:

1  Packagecom.paddx.test.collection;2 3 Importjava.util.ArrayList;4 Importjava.util.LinkedList;5 6  Public classListtest {7      Public Static voidMain (string[] args) {8          for(inti=0;i<10000;i++){9 Ten         } One         LongStart =System.currenttimemillis (); A  -linkedlist<integer> LinkedList =NewLinkedlist<integer>(); -          for(inti=0;i<100000;i++){ theLinkedlist.add (0, i); -         } -  -         LongEnd =System.currenttimemillis (); +SYSTEM.OUT.PRINTLN (End-start); -  +Arraylist<integer> ArrayList =NewArraylist<integer>(); A          for(inti=0;i<100000;i++){ atArraylist.add (0, i); -         } -  -System.out.println (System.currenttimemillis ()-end); -     } -}

The following is the result of local execution:

231227

It can be seen that in this case, the insertion efficiency of linkedlist is much higher than that of ArrayList, of course, this is a more extreme situation. Let's compare the efficiency of the two random accesses:

1  Packagecom.paddx.test.collection;2 3 Importjava.util.ArrayList;4 Importjava.util.LinkedList;5 ImportJava.util.Random;6 7  Public classListtest {8      Public Static voidMain (string[] args) {9 TenRandom random =NewRandom (); One  A          for(inti=0;i<10000;i++){ -  -         } thelinkedlist<integer> LinkedList =NewLinkedlist<integer>(); -          for(inti=0;i<100000;i++){ - Linkedlist.add (i); -         } +  -Arraylist<integer> ArrayList =NewArraylist<integer>(); +          for(inti=0;i<100000;i++){ A Arraylist.add (i); at         } -  -         LongStart =System.currenttimemillis (); -  -  -          for(inti=0;i<100000;i++){ in             intj = Random.nextint (i+1); -             intK =Linkedlist.get (j); to         } +  -         LongEnd =System.currenttimemillis (); theSYSTEM.OUT.PRINTLN (End-start); *  $          for(inti=0;i<100000;i++){Panax Notoginseng             intj = Random.nextint (i+1); -             intK =Arraylist.get (j); the         } +  ASystem.out.println (System.currenttimemillis ()-end); the     } +}

Here are the results of my native execution:

52776

It is clear that ArrayList's random access efficiency is several orders of magnitude higher than linkedlist. Through these two pieces of code, we should be able to clearly know the difference between LinkedList and ArrayList and adapt to the scene. As for vectors, it is a thread-safe version of ArrayList, and the stack corresponds to the stack data structure, which is less used, and here is not an example.

(2) Queue: Can generally be done directly using LinkedList, from the above class diagram can also be seen, LinkedList inherit from Deque, so LinkedList has the function of double-ended queue. Priorityqueue is characterized by providing a priority for each element, with high priority elements prioritizing the queue.

(3) The main difference between Set:set and list is that set does not allow elements to be duplicated, while list allows elements to be duplicated. The repetition of the judging element needs to be determined by the object's hash method and the Equals method. This is also why we typically override the Hashcode method and the Equals method for the element class in the collection. Let's take a look at the difference between set and list, and how the Hashcode method and the Equals method work:

 Packagecom.paddx.test.collection;Importjava.util.ArrayList;ImportJava.util.HashSet;ImportJava.util.Set; Public classSettest { Public Static voidMain (string[] args) {person P1=NewPerson ("Lxp", 10); Person P2=NewPerson ("Lxp", 10); Person P3=NewPerson ("Lxp", 20); ArrayList<Person> list =NewArraylist<person>();        List.add (p1); System.out.println ("---------");        List.add (p2); System.out.println ("---------");        List.add (p3); System.out.println ("List size=" +list.size ()); System.out.println ("----Split Line-----"); Set<Person> set =NewHashset<person>();        Set.add (p1); System.out.println ("---------");        Set.add (p2); System.out.println ("---------");        Set.add (p3); System.out.println ("Set size=" +set.size ()); }    Static classperson{PrivateString name; Private intAge ;  PublicPerson (String name,intAge ) {             This. Name =name;  This. Age =Age ; } @Override Public Booleanequals (Object o) {System.out.println ("Call Equals (); Name=" +name); if( This= = O)return true; if(O = =NULL|| GetClass ()! = O.getclass ())return false; Person Person=(person) o; returnname.equals (person.name); } @Override Public inthashcode () {System.out.println ("Call Hashcode (), age=" +Age ); returnAge ; }    }}

The execution results of the above code are as follows:

------------------List size=3----Split Line-----call Hashcode (), age=10---------call Hashcode (), Age=10call equals () name= LXP---------Call Hashcode (), Age=20set size=2

As a result, the elements are added to the list without additional action and can be duplicated. The Hashcode method needs to be executed before the set is added, and if the returned value already exists in the collection, you continue to execute the Equals method, and if the result returned by the Equals method is true, it proves that the element already exists and overwrites the old element with the new element. If the return hashcode value is different, the collection is added directly. One thing to remember here is that for elements in a collection, elements with different hashcode values must be unequal, but not equal, hashcode values may be the same.

The difference between HashSet and Linkedhashset is that the latter ensures that the element order of the element's insert collection is consistent with the output order. The difference between tresset is that the sort is sorted by comparator, and by default in ascending order by character's natural sequence.

(4) Iterable: From this diagram you can see that the collection class inherits from the Iterable, which functions as an element traversal function, which means that all collection classes (except the map-related classes) provide the function of element traversal. Iterable contains the iterator iterator, the source code is as follows, if you are familiar with the iterator mode, it should be easy to understand.

1  Public Interface Iterator<e> {23     boolean  hasnext (); 4 5     E Next (); 6 7     void remove (); 8 }

2. Map:

The greatest advantage of a collection of map types is that it is relatively efficient to find and ideally can achieve O (1) time complexity. The most common point in map is that Hashmap,linkedhashmap and hashmap differ in that they ensure that the element order of the inserted set is consistent with the output order. The difference between the two and TreeMap is that TreeMap is sorted according to the key value, of course, its underlying implementation also has an essential difference, such as HashMap bottom is a hash table, and TreeMap's underlying data structure is a tree. We now look at the difference between TreeMap and Linkedhashmap:

 Packagecom.paddx.test.collection;ImportJava.util.Iterator;ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJava.util.TreeMap; Public classMaptest { Public Static voidMain (string[] args) {Map<String,String> TreeMap =NewTreemap<string,string>(); Map<String,String> Linkedmap =NewLinkedhashmap<string, string>(); Treemap.put ("B",NULL); Treemap.put ("C",NULL); Treemap.put ("A",NULL);  for(Iterator<string> iter =Treemap.keyset (). iterator (); Iter.hasnext ();) {System.out.println ("Treemap=" +Iter.next ()); } System.out.println ("----------Split Line---------"); Linkedmap.put ("B",NULL); Linkedmap.put ("C",NULL); Linkedmap.put ("A",NULL);  for(Iterator<string> iter =Linkedmap.keyset (). iterator (); Iter.hasnext ();) {System.out.println ("Linkedhashmap=" +Iter.next ()); }    }}

Run the above code and execute the following results:

Treemap=atreemap=btreemap=c----------Split Line---------Linkedhashmap=blinkedhashmap=clinkedhashmap=a

From the running results can be clearly seen this treemap and linkedhashmap difference, the former is sorted by string output, and the latter is based on the order of insertion output. Careful reader can find that the difference between HashMap and TreeMap, and the HashSet and TreeSet mentioned before the difference is consistent, in the follow-up of the source analysis, We can see that hashset and TreeSet are essentially implemented by HashMap and TreeMap respectively, so their differences are naturally the same. Hashtable is now rarely used, and the main difference with HashMap is that Hashtable is thread-safe, but because of its low efficiency, HASHMAP is usually used in a multithreaded environment, usually with Currenthashmap instead.

Iii. Summary

This article only introduces the Java collection framework and its inheritance relationship in general. In addition to the above classes, the collection also provides collections and arrays two tool classes, in addition, the sorting in the collection is closely related to comparable and comparator. In the following article, the above mentioned classes are implemented in the JDK for detailed analysis of the source code.

Java Collection: Overall structure

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.