java-Base-list Interface

Source: Internet
Author: User

List interface

Users of this interface can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list.

Characteristics:

Orderly access to elements

The collection can have repeating elements, and the Equals method of the element to determine whether it is a repeating element (but actually to determine whether the address is equal )

The element can be null

is an indexed collection that can be used to precisely manipulate the elements in a collection by index

List Interface Common subclasses:

ArrayList,--------Array

LinkedList,-------doubly linked list structure

List interface Common methods:

adding elements : Add (Object E): Adding elements from the end of the collection

Add (int index,object e): Adds an element to the collection at the specified index, and the crude element moves back

Delete element : Remove (Object E): Removes the specified element object from the collection and returns the deleted object

Remove (int index,object e): Removes the element from the specified index, with the returned value being the deleted object

Replace element : set (int index,object e) replaces the element at the specified index with the specified element, and the return value is the element before the substitution

Query element : Get ' (int index) gets the element at the index and returns the element

list<string> list =NewArraylist<string>();//1, add the element. List.add ("Little Red"); List.add ("Xiao Mei"); List.add (Xiaoqiang);//2, insert element. The collection before inserting the element ["Xiao Hong", "Xiao Mei", "Xiao Qiang"]List.add (1, "Lao Wang");//the collection after inserting the element ["Xiao Hong", "Lao Wang", "Xiao Mei", "Xiao Qiang"]//3. Delete the element. List.remove (2);//Delete the element after the collection ["Little Red", "Lao Wang", "Xiao Qiang"]//4. Modify the element. List.set (1, "The Old King Next Door");//the collection after modifying the element ["Little Red", "Old King next Door", "Xiao Qiang"]Iterator<String> it =list.iterator (); while(It.hasnext ()) {String str=It.next (); System.out.println (str);}

Because the list collection has an index, you can also iterate with the index

 for (int i = 0; i < list.size (); i++) {    = list.get (i)    ; System.out.println (str);            }
Concurrency modification exceptions for iterator
 Public classIteratordemo {//in the list collection iteration element, the element is judged and a new element is added once the condition is met     Public Static voidMain (string[] args) {//Create a list collectionlist<string> list =NewArraylist<string>(); //adding elements to the collectionList.add ("ABC1"); List.add ("ABC2"); List.add ("ABC3"); List.add ("ABC4"); //iteration Set, when there is an element of "ABC2", the collection joins the new element "a"Iterator<string> it =List.iterator ();  while(It.hasnext ()) {String str=It.next (); //determines whether the removed element is "ABC2" and adds a new element            if("ABC2". Equals (str)) {List.add ("A");//This action can cause a program error            }        }        //printing elements in a containerSystem.out.println (list); }}

Running the above code has an error JAVA.UTIL.CONCURRENTMODIFICATIONEXCEPTION[L1] What's the reason?

In the iterative process, the elements are manipulated using the methods of the collection. Causes iterators to not know the changes in the collection, which can easily lead to the uncertainty of the data.

Concurrency Modification Exception Workaround: Do not use the method of the collection to manipulate elements when iterating.

Concurrency modification Exceptions

It is possible to manipulate elements through the Listiterator iterator,listiterator, which resolves the error conditions that may occur during the use of iterator iterations.

The list collection stores the structure of the data:

The common structures of data storage are: stacks, queues, arrays, linked lists.

Stack, using the structure of the collection, the access to the element is like the following characteristics:

Advanced back out,

The entry and exit of the stack is the top position of the stack.

Stack: The element is stored. That is, the element is stored at the top of the stack, and the elements in the stack move one position to the bottom of the stack in turn.

Stack: Just take the element. That is, the top position of the stack element is taken out, the stack of elements in turn to the top of the stack to move a position.

queue, using the structure of the collection, the access to the element is like the following characteristics :

Advanced First Out

The entrance of the queue, the side of the exit

Array

find elements Fast: Through the index, you can quickly access the elements at the specified location

add element at the specified index : you need to create a new array, store the specified new element at the specified index, and then copy the original array elements to the new array's corresponding index, based on the index.

To delete an element at the specified index: a new array needs to be created, the original array elements are copied to the position of the new array corresponding to the index, and the specified index position elements in the original array are not copied to the new array

Linked list

Between multiple nodes, connect through an address. For example, many people hold hands, everyone uses their right hand to pull down a person's left hand, and so on, so many people are connected together.

Find elements slow: To find an element, you need to go through the connected node, looking back to the specified element

Delete elements quickly:

Add element: Operation as shown on the left, just modify the address of the next element to be connected.

Delete element: The action, as shown on the right, simply modifies the address of the next element to be connected.

ArrayList Collection

The structure of the ArrayList collection data store is the array structure. elements are slow to delete, Find Fast , because the most used features in daily development for querying data, traversing data, so ArrayList is the most common collection.

Lenkedlist Collection

The structure of the LinkedList collection data store is the linked list structure. A collection of convenient elements to add and delete. The addition and deletion of a collection element in real-world development often involves end-to-end operations, while LinkedList provides a large number of methods for end-to-end operations.

LinkedList is a subclass of list, the method LinkedList in list can be used

linkedlist<string> link =NewLinkedlist<string>(); //adding elementsLink.addfirst ("ABC1"); Link.addfirst ("ABC2"); Link.addfirst ("ABC3"); //get ElementSystem.out.println (Link.getfirst ());        System.out.println (Link.getlast ()); //Delete ElementSystem.out.println (Link.removefirst ());                System.out.println (Link.removelast ());  while(!link.isempty ()) {//determines whether the collection is emptySystem.out.println (Link.pop ());//the top element of the stack in the popup collection}

the structure of the vector collection data store is the array structure, which is the oldest provided collection in the JDK. The vector provides a unique way to take out, which is to enumerate enumeration, which is actually an early iterator. the vector collection has been replaced by ArrayList. Enumeration enumeration has been replaced by Iterators iterator.

The difference between list and array:

In the same place:

Can represent a group of objects of the same type

are indexed using the subscript

The difference:

Arrays can store any type of element

List cannot store basic data types and needs to be packaged

Fixed array size, list can grow dynamically

Array efficiency is high; List is less efficient because it needs to maintain extra content

Summarize:

Arrays are preferred when capacity is fixed, accommodating more types and more efficient

List is more advantageous in the case of uncertain capacity

ArrayList expansion mechanism:
 Public BooleanAdd (E object) {object[] a=Array; ints =size; //when full, enlarge    if(s = =a.length) {//Min_capacity_increment is a constant,object[] NewArray =NewObject[s +(S< (MIN_CAPACITY_INCREMENT/2)?min_capacity_increment:s>> 1)]; System.arraycopy (A,0, NewArray, 0, s); Array= A =NewArray; } A[s]=object; Size= s + 1; Modcount++; return true;}
    • When the number of elements in the ArrayList is less than 6 o'clock and the capacity reaches the maximum, the element capacity is amplified by 12;
    • Conversely, increase the current number of elements by half.

linkedlist expansion mechanism:
 Public BooleanAdd (E object) {returnAddlastimpl (object);}Private BooleanAddlastimpl (E object) {Link<E> Oldlast =voidlink.previous; Link<E> NewLink =NewLink<e>(object, Oldlast, Voidlink); Voidlink.previous=NewLink; Oldlast.next=NewLink; Size++; Modcount++; return true;}

You can see LinkedList no expansion mechanism!

This is because the linedlist is actually a doubly linked list, there is no limit to the number of elements, hard to add on the line.
transient Link<e> Voidlink; Private Static Final class Link<et> {    ET data;    Link<ET> Previous, next;    Link (ET o, link<ET> p, link<et> N) {        = o;         = p;         = n;    }}
There are two ways to convert an array in the list:

Object[] ToArray ()

Returns an array containing all the elements in the list;

T[] ToArray (t[] array)

The effect is the same as when the parameter array is larger than the list element, the element in the list is saved using the parameter array, otherwise a new array is created to hold all the elements in the list;

java-Base-list Interface

Related Article

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.