& Lt; Java & gt; hacker from the Collection framework, java hacker

Source: Internet
Author: User

<Java> the hacker from the Collection framework and the java hacker
Preface

The Collection framework is to provide an object or container for storing things. It is easy to understand, just like a database. It provides functions such as adding, deleting, modifying, and querying data, java provides excellent support for the Collection framework. All are placed in java. util. The core interfaces include Collection, Set, List, Map, SortedMap, SortedSet, and so on. Common Implementation classes include ArrayList, HashMap, and HashSet.

List ①

Basic Introduction:

The List interface is a sub-interface of Collection. The Chinese name can be "List" or "List". Its sequence and length are fixed. Both the array structure and the linked list structure are a special form of list.

Common Implementation classes:

ArrayList: it is an array-based structure with no special relationship between nodes. The default size is 10 and the maximum size is Integer. MAX_VALUE-8. When the size is not enough, it will automatically increase. It can directly obtain and modify the data of a node through get and set.

LinkedList: it is a structure based on a two-way linked list. Each node has two pointers pointing to the previous node and the next node respectively. It is variable length.

The difference between the two implementation classes is that the get ()/set () Efficiency of the ArrayList is higher than that of the aggregate list, while the add ()/remove () Efficiency of the aggregate list is higher than that of the ArrayList.

Specifically, the size of an array applying for a continuous memory space is determined during compilation and cannot be dynamically changed during runtime. But why can the ArrayList be changed, if the value of add exceeds the set size, a new larger (growth rate seems to be 0.5) ArrayList will be created, and the original list will be copied to the new list, and point the address to the new list. The old list is recycled by GC, which obviously consumes a lot of memory and is very inefficient. However, because the applied memory space is continuous, you can directly obtain the required data by subscript. the time complexity is O (1), while the linked list is O (n ),

The linked list structure is different. It can dynamically apply for memory space. The pointer to the previous node to be added is unlinked and directed to the new plus node. Then, the pointer to the new plus node is directed to the next node. Fast.

Therefore, ArrayList is suitable for query, and sorted list is suitable for addition and deletion.

Others:

You can use the auxiliary tool Collections. sort () to sort the List. However, you must overwrite the compare method of objects in the list. The following is a reference example of Java 8.

package com.vogella.java.collections.list;import java.util.ArrayList;import java.util.List;public class ListSorter {  public static void main(String[] args) {    System.out.println("Sorting with natural order");    List<String> l1 = createList();    l1.sort(null);    l1.forEach(System.out::println);        System.out.println("Sorting with a lamba expression for the comparison");    List<String> l2 = createList();    l2.sort((s1, s2) -> s1.compareToIgnoreCase(s2));  // sort ignoring case    l2.forEach(System.out::println);        System.out.println("Sorting with a method references");    List<String> l3 = createList();    l3.sort(String::compareToIgnoreCase);       l3.forEach(System.out::println);           }    private static List<String>  createList() {    List<String> list = new ArrayList<>();    list.add("iPhone");    list.add("Ubuntu");    list.add("Android");    list.add("Mac OS X");    return list;  }}

By the way, I will introduce the Collections class. I believe that you have encountered the difference between collection and collections during the java basic interview questions. Now you should understand that they are the upper-layer interfaces of the collection framework, list and set are their sub-interfaces. One is the auxiliary class of the Collection framework. In addition to sorting, Collections also provides many other methods, such as copy (list, list) copy a list to another list (note that this is different from list = list). The former has two lists in the heap, although the content is the same, the latter has only one list in the heap, but the stack has two references pointing to it. There is also a reverse (list), which obviously reverse the list, and shuffle (list) disrupt the list order, and many others. Therefore, when you need to perform operations on the list data, don't try to do it by scratching your head. Go to Collections to find out if there are any methods you have already written.

Set ①

Basic Introduction:

Set is also a sub-interface of Collection. The Chinese name can be "set". Anyone who has studied High School Mathematics knows that set is a mathematical concept and has three features.

Certainty: each element in the set is deterministic.

Sequent: the positions of each element in the set are arbitrary.

Interaction: each element in the set is different. {1, a} Then a cannot be equal to 1;

The set in the computer field or advanced language also has these three features. In Java, Set is used.

Certainty: No need to explain. (Up to one null value)

No sequence: The Collections. sort () is invalid for the set, and the importance of the list sequence is also explained from the aspect.

Opposite Sex: The Set interface only inherits the Collection method and adds the distinct constraint. In the Set interface, equals is used to determine whether the elements are the same, this requires that the equals and hashcode methods of the Set elements are very important. It is clear that if the elements in the two sets are the same, the two set instances are the same.

  

        Set<String> stringSet = new HashSet<>();        stringSet.add("aaa");        stringSet.add("bbb");        stringSet.add("ccc");        stringSet.add("ddd");        stringSet.add("eee");        Set<String> stringSet1 = new TreeSet<>();        stringSet1.add("aaa");        stringSet1.add("bbb");        stringSet1.add("ccc");        stringSet1.add("ddd");        stringSet1.add("eee");        System.out.println(stringSet.equals(stringSet1));    
     /////
     Output>>true

 

Common Implementation classes:

HashSet: it is a very good Set implementation class and is stored based on a hash table, but it does not guarantee the order of the returned Iterator (Iterator.

TreeSet: it is stored Based on the red/black tree. It sorts Set elements by value, which is much slower than HashSet.

LinkedHashSet: it is also stored in a hash table, but it is added with a linked list to save its element insertion sequence. That is to say, when it is output cyclically, it will be output according to the insertion sequence. Obviously, in order to achieve this effect, we can sacrifice a large amount of efficiency.

Map ①

Basic Introduction

Map is a set of many key-value pairs, because its principle is not the same as the data structure of the set, it is not inherited from the Collection, and Map is the highest level interface. The key of the map cannot be repeated, and each key can correspond to a maximum of one value. (It is worth noting that the Map interface replaces the Dictionary abstract class of the old version ). Map provides three sets to traverse the map, namely, keySet (), values (), and entrySet (). Note that the view and Element Set copy are different, the former is much more efficient.

Common Implementation class

HashMap :*

TreeMap :*

LinkedHashMap :*

We can see that these maps are the same as the common classes in the above Set. Why? In fact, the Map key is actually implemented by using set. The set type is the map type. The map order is the same as the set above.

Conclusion

In summary, before selecting a collection framework, we need to consider the following issues:

1. What type of data? --> Decide whether to use Map or Collection.

2. Is sequence important? --> Decide whether to use list or set.

3. Is the data volume large? --> Decide whether to use highly efficient Linked */Tree * at the cost of efficiency *.

4. Is there a thread security issue (I didn't mention it above )? --> For ArrayList, Vector is recommended because the thread is unsafe. For HashMap, ConcurrentHashMap is recommended because the thread is insecure.

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.