Java (Article 3 and 2) ----- List summary, java ----- list Summary

Source: Internet
Author: User

Java (Article 3 and 2) ----- List summary, java ----- list Summary

Previously, LZ has fully introduced most of the knowledge about the List interface, such as ArrayList, List, Vector, and Stack. Through these knowledge points, we can have a deep understanding of the List interface. Only the summarized knowledge is your knowledge. Therefore, the LZ below makes a summary of the List interface. Recommended reading:

Java (ii) ----- ArrayList

Java (ii) ----- upgrade list

Java (II 9) ----- Vector

Java (Sany) ----- Stack

1. List interface Overview

The List interface becomes an ordered Collection, that is, a sequence. This interface can precisely control the insert position of each element in the list. You can also access the element based on the integer index of the element (the position in the list) and search for the element in the list. Is the framework of the List interface:


Through the above frame chart, you can understand the structure of the List. Its classes and interfaces are as follows:

Collection:The Root Interface in the Collection hierarchy. It represents a group of objects, also known as collection elements. For Collection, it does not provide any direct implementation, and all the implementation is the responsibility of its subclass.

AbstractCollection:The backbone implementation of the Collection interface is provided to minimize the work required to implement this interface. To implement an unchangeable collection, we only need to extend this class and provide implementation of the iterator and size methods. To implement a modifiable collection, you must overwrite the add method (otherwise, UnsupportedOperationException will be thrown). The iterator returned by the iterator method must also implement its remove method.

Terator:Iterator.

ListIterator:The series table iterator allows programmers to traverse the list in any direction, modify the list during iteration, and obtain the current position of the iterator in the list.

List:The Collection interface. It represents an ordered queue.

AbstractList:The backbone implementation of the List interface to minimize the work required to implement the interface supported by random access data storage (such as arrays.

Queue:Queue. Provides basic queue insertion, retrieval, and inspection operations.

Deque:A linear collection that supports inserting and removing elements at both ends. Most Deque implementations have no fixed limit on the number of elements they can contain. However, this interface supports both capacity-limited and non-fixed-size dual-end queues.

AbstractSequentialList:Provides the backbone implementation of the List interface, thus minimizing the work required to implement this interface supported by "continuous access" Data Storage (such as the link List. In a sense, this class is similar to implementing the "Random Access" method on the list iterator of the list.

Shortlist:List interface. It implements all optional list operations.

ArrayList:The implementation of Variable-size array of the List interface. It implements all optional list operations and allows all elements including null. In addition to the List interface, this class also provides some methods to internally store the size of the List array.

Vector:An array of objects that can be increased. Like an array, it contains components that can be accessed using integer indexes.

Stack:The object stack of LIFO. It extends the Vector class through five operations, allowing the Vector to be considered as a stack.

Enumeration:Enumeration, which implements the object of this interface. It generates a series of elements and generates one at a time. Consecutive calls to the nextElement method will return a series of continuous elements.


II. Application scenarios

The fundamental purpose of learning knowledge is to use it.Each knowledge point has its scope of use. The same is true for collections. The integration family in Java is very large, and each member has the most suitable application scenarios. When I first came into contact with List, LZ saidIf operations such as "stack", "queue", and "linked List" are involved, use List first.The List is classified as follows:

1. to quickly insert or delete an element, you need to use the sort list.

2. for elements that require quick access, use ArrayList.

3. For "Single-threaded environment" or "multi-threaded environment, but the List is operated by only one thread", consider using non-synchronous classes. If it is a "multi-threaded environment, splitting a List may be operated by multiple threads at the same time. "Use a synchronous class (such as Vector ).

2.1 ArrayList and javaslist Performance Analysis

In List, the most common examples are 'arraylist' and 'arraylist'. At the same time, we understand the application scenarios and differences between them.

Public class ListTest {private static final int COUNT = 100000; private static ArrayList arrayList = new ArrayList <> (); private static argument list addition list = new argument list <> (); private static Vector vector = new Vector <> (); public static void insertToList (List list) {long startTime = System. currentTimeMillis (); for (int I = 0; I <COUNT; I ++) {list. add (0, I);} long endTime = System. currentTimeMillis (); System. out. println ("insert" + COUNT + "element" + getName (list) + "cost" + (endTime-startTime) + "millisecond ");} public static void deleteFromList (List list) {long startTime = System. currentTimeMillis (); for (int I = 0; I <COUNT; I ++) {list. remove (0);} long endTime = System. currentTimeMillis (); System. out. println ("delete" + COUNT + "element" + getName (list) + "cost" + (endTime-startTime) + "millisecond ");} public static void readList (List list) {long startTime = System. currentTimeMillis (); for (int I = 0; I <COUNT; I ++) {list. get (I);} long endTime = System. currentTimeMillis (); System. out. println ("read" + COUNT + "element" + getName (list) + "cost" + (endTime-startTime) + "millisecond ");} private static String getName (List list) {String name = ""; if (list instanceof ArrayList) {name = "ArrayList";} else if (list instanceof parameter List) {name = "shortlist";} else if (list instanceof Vector) {name = "Vector";} return name;} public static void main (String [] args) {insertToList (arrayList); insertToList (partition list); insertToList (vector); System. out. println ("------------------------------------"); readList (arrayList); readList (linear list); readList (vector); System. out. println ("------------------------------------"); deleteFromList (arrayList); deleteFromList (linkedefromlist); deleteFromList (vector );}}

Running result:

Inserting 100000 elements of ArrayList takes 3900 milliseconds to insert 100000 elements of ArrayList takes 15 milliseconds to insert 100000 elements of Vector takes 3933 milliseconds -------------------------------- reading 100000 elements of ArrayList takes 0 milliseconds to read 100000 elements of ArrayList takes 8877 milliseconds to read 100000 Elements it takes 16 milliseconds ------------------------------------ to delete the 100000 element ArrayList. It takes 4618 milliseconds to delete the 100000 element ArrayList. It takes 16 milliseconds to delete the 100000 element Vector. It takes 4759 milliseconds.

From the above running results, we can clearly see the efficiency of ArrayList, sorted list, and Vector addition, deletion, and traversal. Next I will insert the add (int index, E element) method, delete, and get methods. If you are interested, you can study them.

First, let's look at the source code between the three:

ArrayList

Public void add (int index, E element) {rangeCheckForAdd (index); // check whether the index is valid ensureCapacityInternal (size + 1); // resize the System. arraycopy (elementData, index, elementData, index + 1, size-index); // copy the array elementData [index] = element; // insert size ++ ;}

The rangeCheckForAdd and ensureCapacityInternal methods have no influence on the System. arraycopy method, which is a JNI function and implemented in JVM. The statement is as follows:

public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

Currently, LZ cannot see the source code, but the specific implementation is not very clear. However, the source code analysis of System. arraycopy is clear. But in fact, we only need to know that this method will move all the elements behind the index, which means the add (int index, E element) of the ArrayList) the method will change all the elements after the index position.

Shortlist

Public void add (int index, E element) {checkPositionIndex (index); if (index = size) // The insert position is at the end of linkLast (element); else linkBefore (element, node (index ));}

This method is relatively simple. If the insert position is at the end, the linkLast method is called. Otherwise, the linkBefore method is called. In fact, linkLast and linkBefore are very simple implementations, that is, inserting elements at the index position, if the index is specific, the node method is used to solve the problem. At the same time, node accelerates index location retrieval, as shown below:

Node <E> node (int index) {if (index <(size> 1 )) {// If the index is smaller than size/2, search for Node <E> x = first; for (int I = 0; I <index; I ++) x = x. next; return x;} else {// If the index is greater than size/2, search for Node <E> x = last; for (int I = size-1; i> index; I --) x = x. prev; return x ;}}

Therefore, the insert action of the tranquility list is faster than that of ArrayList. 1: You do not need to perform the element copy action on the pull list. 2: There is an accelerated action to find the insert position. That is, if index <1/2 of the length of the two-way linked list, it is searched from the front to the back; otherwise, it is searched from the back to the back.

Vector

The implementation mechanism of Vector is the same as that of ArrayList. dynamic arrays are also used, so the efficiency between them is similar. The source code of add is also the same, as shown below:

public void add(int index, E element) {        insertElementAt(element, index);    }        public synchronized void insertElementAt(E obj, int index) {        modCount++;        if (index > elementCount) {            throw new ArrayIndexOutOfBoundsException(index                                                     + " > " + elementCount);        }        ensureCapacityHelper(elementCount + 1);        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);        elementData[index] = obj;        elementCount++;    }

The above is an explanation of the add (int index, E element) method between ArrayList, struct list, and Vector, it explains why the insert action of the sort list is much more efficient than that of ArrayList and Vector! As for the delete and get methods, LZ will not be explained much.

At the same time, LZ found a very interesting phenomenon when writing the above example, that is, the explain list method will be slower than the ArrayList method when executing the add method in some cases! What is the situation? Why is it slow down LZ's next blog explanation? Of course, I don't know if you have encountered this problem ??

2.2 differences between Vector and ArrayList


4. More

Java (ii) ----- ArrayList

Java (ii) ----- upgrade list

Java (II 9) ----- Vector

Java (Sany) ----- Stack

----- Original text from: Http://cmsblogs.com /? P = 1201 Please respect the author's hard work and repost the source.

----- Personal site:Http://cmsblogs.com


Java helps to summarize some content in the java object-oriented advanced article

1. Inheritance: inheritance is a hierarchical model that connects classes and allows reuse of encouraging classes. It provides a clear way to express commonalities. A new class of the object
To derive from an existing class. This process is called class inheritance. The new class inherits the features of the original class. The new class is called the derived class of the original class (subclass), and the original class is called
The base class (parent class) of the new class ). A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make it more suitable for special
Yes.
2. Polymorphism: allows different types of objects to respond to the same message. Polymorphism includes parameterized polymorphism and inclusion polymorphism. Polymorphism
The advantages of activity, abstraction, behavior sharing, and code sharing effectively solve the same name problem of application functions.
3. encapsulation: encapsulate processes and data, and access to data can only be performed through the defined interface. Object-oriented computing begins with this basic concept, that is, the real world
It can be depicted as a series of completely autonomous and encapsulated objects that access other objects through a protected interface.
4. string processing: The StringBuffer and StringBuilder classes that are specially processed to save space
5. Abstraction: Abstraction ignores those aspects irrelevant to the current target in a topic, so that you can pay more attention to the aspects related to the current target. Abstract.
To solve all the problems, select only one part. Abstract: Process abstraction and data abstraction.
6. mechanisms made to handle runtime and compilation exceptions.
7. is the upgraded version of the array, and the bottom layer of the set is also an array. however, a set can be of multiple types, not just a basic type. the Set also allows you to add, delete, query, and modify data in the set more conveniently and quickly.

A java training summary, more than 1500 words (Internship summary at university graduation)

You can find it on the paper website.
 

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.