Java Basics-Collection Source parsing List List interface

Source: Internet
Author: User

Today we are going to learn the first big system List of the collection.

A List is an interface that defines a set of elements that are ordered and repeatable.

The List inherits from Collection, and the following methods of operation are added compared to collection,list

    • Positional correlation: The elements of the List are ordered, so there is a get (index), set (Index,object), add (Index,object), and remove (index) method.
    • Search: IndexOf (), lastIndexOf ();
    • Iteration: A functional board iterator using Iterator
    • Scoping action: Use the Sublist method to manipulate the list in any scope.
The abstract implementation class of List Abstractlist

Abstractlist inherits from the Abstractcollection class and implements the List interface. The entire class is designed to resemble abstractcollection, implementing most methods, and abstracting the methods that need to be manipulated based on data.

The implementation class of List ArrayList

ArrayList is one of our most commonly used classes, and it has the following characteristics:

    • Capacity is not fixed, can be dynamically expandable
    • Orderly (array-based implementations, of course, ordered ~ ~)
    • The element can be null
    • High efficiency
      • The time complexity of the find operation is O (1)
      • The time complexity of adding and deleting operations is O (n)
      • All other operations are basically O (n)
    • takes up less space and uses no additional space to maintain table structure compared to LinkedList

From the member variables, we can learn

    • Object[] Elementdata: Data structure---array
    • Two default empty arrays, used only in construction methods, do not care about
    • Default_capacity: Array initial capacity is 10
    • Size: Current number of elements
    • Max_array_size: Array Maximum capacity

Now we know that ArrayList is actually an array-based implementation. Therefore, adding and removing changes to the operation becomes very easy to understand.

    • Get (index) gets the bottom index element of the array directly
    • Set (Index,object) directly modifies the reference of the index element of the array
    • Add (index,object) adds an element to index, where the expansion of the array is involved, and the expansion is then seen separately.

The operation here is very simple, for example, an array of 8 elements, to insert an element x in the fifth position, the elements of the [5,8] corner will be moved backward one to [6,9], when the position of the corner labeled 5 is empty, so array[5] = x.

    • Remove (object) removes an element from the same element that is added to the process.

Now let's take a look at the scaling mechanism, assuming we now have a list of collections with exactly 10 elements in it, we call the Add (object) method, adding an element to see how the scaling operation is performed.

public boolean Add (E var1) {//See if the array length is sufficient this.ensurecapacityinternal (this.size    + 1);    this.elementdata[this.size++] = var1; return true;} private void ensurecapacityinternal (int var1) {//Check if is the default length of 0 array, if it is the length is set to ten if (This.elementdata = = Defaultcapacity_e    Mpty_elementdata) {var1 = Math.max (ten, var1); } this.ensureexplicitcapacity (VAR1);}    private void ensureexplicitcapacity (int var1) {++this.modcount;    The current required length is greater than the array length, performing an expansion operation if (Var1-this.elementdata.length > 0) {this.grow (var1);    }}private void Grow (int var1) {int var2 = this.elementData.length;    VAR3 = var2*1.5; expansion 1.5 times times int var3 = var2 + (var2 >> 1);    if (Var3-var1 < 0) {var3 = var1;    }//new capacity exceeds maximum if (var3-2147483639 > 0) {var3 = Hugecapacity (var1); }//re-created a 1.5 times-fold array assignment to Elementdata this.elementdata = arrays.copyof (This.elementdata, VAR3);} 

As we can see from the above, we can directly invoke the operation of the array when we modify the value of a certain corner mark or find the value of a corner label, which is highly efficient. However, adding and deleting is a little less efficient to manipulate the movement of the entire array.

As we can see here, the ArrayList is actually a wrapper class for array manipulation.

LinkedList

We have just looked at the arraylist,arraylist of the operation efficiency is relatively low. As a result, Java has designed another set of linkedlist that is more efficient to delete.

LinkedList inherits from Abstractsequentiallist.

Abstractsequentiallist also inherits from Abstractlist, and realizes the default additions and deletions based on iterator.

Look back to see Linkedlist,linkedlist also implemented the Deque (bidirectional queue) interface, two-way queue after we will go to study alone, here no longer do too much to repeat.

Take a look at the member variables ~ ~

    • Size Linked list element number
    • First one element
    • Last element

Characteristics? and the advantages and disadvantages of ArrayList complementary.

The implementation of the linked list, the implementation of the list is very simple, is the most basic linked list data structure. Understanding the linked list data structure can be skipped here.

I would like to give an example, now let A, B, C, d four students in the order of shooting. There are two ways, the first is ABCD into a team, and then to shoot, but in physical education to let all the students waiting for the shooting is a waste of time, so there is a second way: In turn, tell a ' you voted blue after the B to shoot ', tell B ' you voted blue after the C to shoot ' and so on.
In this way, a simple one-way list is formed, in which ABCD shoots the shots sequentially. At this time, X classmate because the body is not comfortable need to shoot back to the classroom to rest, then the teacher only need to tell a classmate after throwing the basket do not have to call B classmate, change called X classmate, X classmate after the basket is called B classmate can.
Not much to say, novice do not understand, veteran use not. Do not understand the list of students to learn to learn the data structure it.

After the additions and deletions to the operation is only the basis of the traversal of the list operation, do not go to one by one to read the source, linked list operation not too clear students can go to see the source of LinkedList.

Vector

After learning the ArrayList, the Vector class I want to use "thread-safe ArrayList" can be summed up in a nutshell.

Vectors and ArrayList inherit from the Abstractlist, why say "vector is thread-safe ArrayList", it was also prepared to make a table to compare the member variables and the implementation of the main operation method. But, in addition to the Vector method on a synchronized, the code is the same, compared to a fur. Therefore, if you need to consider thread safety, you can use the Vector directly, but because all methods are added synchronized, the efficiency is relatively low, if there is no thread-safe demand, then use ArrayList chant.

Finally, let's talk about the difference between vector and ArrayList, anyway, there is no egg to use, everybody look good

    • The Vector was born early, JDK1.0, and ArrayList was born 1.2.
    • Vector is thread-safe, ArrayList is not. (This is the biggest feature of all)
    • Vectors are expanded by default by twice times, and ArrayList is 1.5 times times. Does this make sense?
    • Vector more than one iterator enumeration. Well, I didn't use it anyway.
Enumeration

In order to find out what the characteristics of this iterator, I went over the Vector code, found a way and such an interface, you feel enumeration.

Public enumeration<e> elements () {    return new enumeration () {        int count = 0;        public boolean hasmoreelements () {            return this.count < Vector.this.elementCount;        }        Public E nextelement () {            Vector var1 = vector.this;            Synchronized (vector.this) {//difference here                if (This.count < Vector.this.elementCount) {                    return Vector.this.elementData (this.count++);                }            }            throw new Nosuchelementexception ("Vector enumeration");}}    ;} Public interface Enumeration<e> {    boolean hasmoreelements ();    E nextelement ();}

MMP, what's the difference between this enumeration and the iterator interface except the name? Then read it carefully, inside the anonymous inside of the elements () method, found inside the Nextelement () method There is a synchronous code block. Okay, enumeration probably a thread-safe iterator?

Stack

The Stack inherits from the vector and is also a thread-safe collection.

The Stack is also based on an array implementation.

Stack implements a collection of stacks structure

What is a stack structure?

In data structure, the stack is also a linear data structures, adhering to the LIFO (LIFO) sequence of operations, here with a very dirty diagram, to ensure that you can memorize the stack structure features after reading.

Childhood must have played badminton, badminton does not play, to often change the ball, so I bought a box of badminton, such as, is a badminton box, the first to put in the badminton (bottom of the stack), to finally be taken out.

The code implementation of the Stack

Class structure diagram below, the code is not too much, altogether only 30 a few lines

public class Stack<e> extends vector<e> {private static final long SE    Rialversionuid = 1224463164541339165L;        Public stack () {}//into the stack, adding an element to the last public E push (e var1) {this.addelement (var1) of the array;    return var1;        }//out of the stack, delete the last element of the array and return public synchronized E pop () {int var2 = This.size ();        Object var1 = This.peek ();        This.removeelementat (var2-1);    return var1;        }//Gets the last element without deleting public synchronized E peek () {int var1 = This.size ();        if (var1 = = 0) {throw new emptystackexception ();        } else {return this.elementat (var1-1);    }} public Boolean empty () {return this.size () = = 0;    Gets the position in the stack.        public synchronized int Search (Object var1) {int var2 = This.lastindexof (var1);    return var2 >= 0?this.size ()-var2:-1; }}

The implementation of the whole class is very simple, is to inherit the Vector, and then add Peek, pop, push, search, and so on, and then add the deletion is at the end of the element to do the operation.

Thinking: How to use the structure of a linked list to quickly achieve linkedliststack?

Java Learning Exchange QQ Group: 589809992 prohibit small talk, non-happy do not enter!

Java Basics-Collection Source parsing List List interface

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.