Collection set framework learning notes in JavaSE (1) -- List with indexes, javasecollection
Preface:Because we are looking for a new job recently, Collection is a basic research site with a high frequency during interviews.
During the review process, I felt that my previous study was unsystematic and that I could not answer questions like my new graduation. For example, String is fixed length, and the length of StringBuffer and StringBuilder can be changed. If you have a deep understanding of the difference, you can only look at the interviewer with a look.
Therefore, we want to systematically summarize the learned content, such as what the Collection architecture is and what inheritance and interface implementation are, so that we can know when to use the class, and how to work together between classes to know how to solve the problem. This series of articles applies to students of Java Technology posts, students of computer science in colleges and universities, and students of training institutions studying Java.
1.1 understand Collection Architecture
We have used the ArrayList class to collect objects. For example, the add () method adds objects and the remove () method removes objects. But how did these methods come from? Is the inheritance architecture diagram of this class:
The ArrayList class is so complicated. If you want to present all the Collection architectures on a single graph, it is estimated that it is just as ambiguous as Spider's. To simplify the process, ignore some less important interfaces and implementation classes. We can get the following Architecture diagram.
As shown in the figure, Colletion is an interface that implements the Iterable interface. There are three interfaces under the Collection to implement it directly, namely List, Set and Queue. There are two implementation classes under List: ArrayList and sorted List. The common implementation classes of Set are TreeSet and HashSet. The Deque interface is implemented under Queue, and the ArrayDeque implementation class is shown below.
This figure will be the core of this series of articles, which will be repeatedly mentioned later. It may be called a Collection architecture diagram. each article is part of the introduction. Familiarizing yourself with this image not only helps you understand and learn, but also helps you remember it. As for the detailed inheritance relationship and implementation architecture, You can query the classes that implement the interfaces and inherit the classes in the API instructions.
1.2 List with indexes
List implements the Collection interface, so we can say that List is a kind of Collection, which is used to collect objects. It is characteristic of recording the Collection object order in the way of indexing. The common implementation class in List is the ArrayList in the architecture diagram just mentioned. If you forget it, you can refer to the previous section for reference.
1/** 2 * experiment case of ArrayList 3 */4 5 import java. util. *; 6 7 public class Student {8 public static void main (String [] args) {9 List list = new ArrayList (); // use the JavaSE List and ArrayList10 upload records = new records (System. in); 11 String name; 12 while (true) {13 System. out. print ("Student sign-in:"); 14 name = student. nextLine (); 15 if (name. equals ("quit") {16 break; 17} 18 list. add (name); // use the Add () method to collect objects 19} 20 System. out. println ("list of students who come to class today:"); 21 foreach (List); 22} 23 24 private static void foreach (list) {25 for (int I = 0; I <list. size (); I ++) {26 String student = (String) list. get (I); // use the get () method to retrieve the collected object based on the index 27 System. out. println (student); 28} 29} 30}
The above is a simple example of the ArrayList class, simulating the scenario of students signing in to class. It is strongly recommended that you try to write a simple use case like me, especially for beginners who seldom used ArrayList before. The effect of reading and reading alone is totally different from that of actually coding. You can also follow the examples I have given. If you are a little lazy, you can directly copy and run it on the machine.
From the Collection architecture diagram, the listlist interface is also implemented. Even if you change all the ArrayList in the above experiment to the role list, the program can still operate and the effect looks exactly the same. So the question is, when should we use the ArrayList and the sequence list?
1.2.1 features of ArrayList
Both trucks and ships can deliver goods. We can choose different transportation modes based on different situations. If the time is tight, the transportation volume is small, and both locations are on land (for example, Beijing to Nanjing), we can use cars. If the time is high and the transportation volume is large, the departure and destination are separated by the ocean (such as Dalian to New York), So shipping is a better choice.
I will be looking for a job when I just graduated. In order to answer the interview, "The ArrayList is like an array, reading speed is fast, but the index needs to be adjusted. The sorted list is like a linked list, and the index adjustment is very good, however, random reading speed is slow ". So let's say, why? 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 section is the source code of JavaSE. We can see that the add () method in ArrayList is very simple, just as we usually use arrays. View more information in the source code and you will find that ArrayList uses an Object array to save the collected objects. This is why "ArrayList is like an array. When considering whether to use ArrayList, we can consider whether to use the array feature.
1.2.2 features of consumer list
When learning the Collection architecture, we may look at the source code and compare the implementation of several basic methods, such as add () and remove. From the implementation of these methods, we can see the features of different implementation classes.
public boolean add(E e) { linkLast(e); return true; } /** * Links e as last element. */ void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
When we see the source code of LinkdedList. add (), we will find that the implementation method is the same as that of the linked list. If the last node is null, the linked list is empty. Therefore, the newly added node is the first node. If the last node is not null, set the newly added node to the next node of the last node as the new end node.
Based on the characteristics of the linked list, we can quickly summarize the following two features: 1. when you want to specify random access to an index, the link method must start from the first element to find the next element, which is inefficient. 2. each element of the link will refer to the next element, which helps adjust the index order.
1.2.3 List Summary
As a List of one of the three Collection camps, index is the biggest feature. We can achieve random access through indexes.
The commonly used implementations of List include ArrayList and List. For their respective features, refer to array and List respectively. When comparing the differences between them, we read the source code and advocate that we should focus on the methods they need to be implemented when comparing different implementation classes of the same interface, such as add () specified in the Collection (), remove.
The List Implementation class, which is common in interviews, is actually Vector, which has the same features as ArrayList. The difference is that Vector is thread-safe and has a high performance overhead. The specific content will be put in future articles about multithreading.
In the summary process, we provide two suggestions for beginners. One is to experiment and write some demos to familiarize themselves with the content learned. The other is to read the source code as far as possible, you also need to know why.
If you like my article, you can scan my personal Public Account "Li wenye's thinking notes ".
I will occasionally push my original thinking articles.