Javase Collection Collection Framework Learning Note (1)--list with index

Source: Internet
Author: User

Foreword: because recently to re-find a job, Collection (collection) is a very high frequency of the interview in the basic point of observation, so good likes and dislikes to complement.

Review the process of deep learning is not systematic, and can no longer like just graduated as the back of the test, for example: string is fixed length, stringbuffer and StringBuilder length can be changed. If once asked in depth, ask why there is such a difference is dumbfounded, only a face to look at the interviewer.

therefore want to write the form of the article, systematically summarize the content of the study, such as the collection architecture, what is the relevant inheritance and interface implementation, so as to understand when to use which class, and how to cooperate with the class, only to know how the problem should be solved. This series of articles is intended for Java technical job candidates, college computer majors, and training organizations to learn Java for beginners.

1.1 Understanding Collection Architecture

We have used the ArrayList class to collect objects, such as the Add () method new Object, the Remove () method removes the object, these are not unfamiliar. But how did these approaches come about? Is the inheritance schema diagram for this class:

ArrayList a class is so complex, if you want to show all the collection architecture on a graph, it's probably as tangled as a spider's web. To simplify, ignoring some of the less important interfaces and implementation classes, we can get the following architecture diagram.

From the figure, Colletion is an interface that implements another interface iterable. Collection below are three interfaces that implement it directly, namely list, set, and queue. The list below has two implementation classes, respectively ArrayList and Linkedlist;set common implementation class is TreeSet and Hashset;queue below has deque interface implementation, and the following is the implementation class Arraydeque.

This picture will be at the heart of this series of articles, which will be mentioned again and again, and may be called the collection frame composition, each of which is part of the story. Familiarity with this map not only helps to understand learning, but also helps memory. As for the detailed inheritance relationship and implementation architecture, which classes implement which interfaces, which classes inherit, can be queried in the API documentation itself.

1.2 List with index

List implements the collection interface, so we can say that list is a kind of colletion, the function is to collect objects, the feature is indexed to record the order of the objects collected. The common implementation class in list is the ArrayList in the schema diagram just mentioned, and the forgotten reader can turn to the front and look at it.

1 /**2 * ArrayList's experimental use cases3  */4 5 ImportJava.util.*;6 7  Public classStudent {8      Public Static voidMain (string[] args) {9List List =NewArrayList ();//use Javase's list and ArrayListTenScanner Scanner =NewScanner (system.in); One String name; A          while(true) { -System.out.print ("Student Registration:"); -Name =scanner.nextline (); the             if(Name.equals ("Quit")) { -                  Break; -             } -List.add (name);//useful Add () method to collect objects +         } -System.out.println ("The list of students coming to class today:"); + foreach (list); A     } at  -     Private Static voidforeach (List list) { -          for(inti = 0; I < list.size (); i++) { -String student = (string) list.get (i);//use the Get () method to obtain collected objects by index - System.out.println (student); -         } in     } -}

The above is a simple use example of the ArrayList class, which simulates the students ' attendance in class. It is strongly recommended that the reader try to write a simple use case as I do, especially for beginners who have seldom used ArrayList before, and the simple reading and writing effect is completely different from the actual knock code. You can also follow the example I give you to knock, lazy words can be copied directly on the machine to run again.

From the collection architecture diagram, LinkedList also implements the list interface. Even if you just change all the ArrayList in the above experiment to LinkedList, the program can still work, and the effect looks exactly the same. So the question is, when should we use ArrayList, and when should we use LinkedList?

Characteristics of 1.2.1 ArrayList

Trucks and ships can carry goods, and we can choose different modes of transport depending on the situation. If time is tight, traffic is small, and two locations are on land (for example, Beijing to Nanjing), then we can use cars, and if there is more time and traffic, between the departure point and the destination between the sea (for example, Dalian to New York), then shipping is a better option.

Just graduated that will be looking for a job, for the interview back "ArrayList image array, read faster, but need to adjust the index is very poor performance; LinkedList like a linked list, the index performance is very good, but the speed of random reads is slower." So we can ask a deep question, why is this so? Find the answer from the source code.

1      Public Boolean Add (e e) {2         ensurecapacityinternal (size + 1);  // increments modcount!! 3         elementdata[size++] = e; 4         return true ; 5     }

The above paragraph is javase source code, we can see that the Add () method in ArrayList is very simple, as we normally use arrays. See more in the source code you will find that the ArrayList inside is using an object array to hold the collected objects, which is why the "ArrayList is like an array". When considering whether to use ArrayList, we can consider whether we want to use the attributes of the array.

Characteristics of 1.2.2 LinkedList

When learning the collection architecture, we may as well look at the source code, look at the time preferred to compare the implementation of a few basic methods, such as add (), remove () and so on. From the implementation of these methods, we can see the characteristics of different implementation classes.

     Public BooleanAdd (e e) {linklast (e); return true; }    /*** Links e as last element. */    voidLinklast (e e) {Finalnode<e> L =Last ; FinalNode<e> NewNode =NewNode<> (L, E,NULL); Last=NewNode; if(L = =NULL) First=NewNode; ElseL.next=NewNode; Size++; Modcount++; }

See the source code of Linkdedlist.add (), we will find that its implementation is the same as the implementation of the list. If the last node is null, then the linked list is empty, so the newly added node is the head node. If the last node is not equal to NULL, then the newly added node is set to the next node of last, as the new tail node.

Based on the nature of the list, we can quickly summarize two point features: 1. When you want to specify random access to an index, the method of linking is used to find the next element starting from the first element, which is inefficient; 2. Each element of the link will refer to the next element, which facilitates the adjustment of the index order.

1.2.3 List Summary

As one of the three collection of the list, the most important feature is the index, we can do random access through the index.

The commonly used implementations in list are ArrayList and LinkedList, each of which can refer to arrays and linked lists, respectively. In the process of comparing the differences between them, we looked at the source code, advocating that when comparing the same interface with different implementation classes, it is important to look at the methods that they collectively need to implement, such as add (), remove (), and so on, as specified in collection.

The common list implementation class in the interview is actually a vector, which has the same characteristics as ArrayList. The difference is that the vector has thread-safe features, the performance overhead is relatively large, the specific content will be placed in later on the multi-threaded article.

In the summary process, to provide beginners with two recommendations, one is to do experiments, by writing some demo to familiarize yourself with the content, and second, in the case of the source code to see more, know it is also to know its why.

If you like my article, you can scan my personal public number "Li Wen's thinking notes".

I will occasionally push my original thinking articles.

Javase Collection Collection Framework Learning Note (1)--list with index

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.