Java Collection Framework Summary (4) Use of the--list interface

Source: Internet
Author: User

Java Collection Framework Summary (4) Use of the--list interface

The list collection represents an ordered collection, and each element in the collection has its corresponding sequential index. The list collection allows you to use duplicate elements, which can be indexed to access the collection elements at the specified location.

1. List interface and Listiterator interface

List as a sub-interface of the collection interface, you can use all the methods in the collection interface. List is an ordered set, so the list collection adds some methods to manipulate the collection elements according to the index:

    • void Add (int index, Object Element): Elements element is inserted at index of the list collection.
    • Boolean addall (int index, Collection c): Inserts all the elements contained in collection C at index of the list collection.
    • Object get (int index): Returns the element at the index of the collection index.
    • int LastIndexOf (object o): Returns the position index of the last occurrence of the object o in the list collection.
    • Object Remove (int index): deletes and returns the element at the index.
    • Object Set (int index, object element): Replace the element at the index index with an element object, returning the new element.
    • List sublist (int fromIndex, int toindex): Returns a subset of all the collection elements from the index FromIndex (contained) to the index Toindex (not included).

The list collection can insert, replace, and delete collection elements based on the index.

Sample program:

public class testlist{public    static void Main (string[] args)    {        List books = new ArrayList ();        Add three elements to the books collection        Books.add (New String ("Lightweight EE Enterprise Application Combat"));        Books.add (New String ("Struts2 authoritative guide"));        Books.add (New String ("Java EE-based AJAX Toolkit"));        SYSTEM.OUT.PRINTLN (books);        Insert the new String object in the second position        Books.add (1, new string ("Ror Agile Development Best Practices")), and//The added object, and compare the following statement for        (int i = 0; i < books.size ( ) ; i++)        {            System.out.println (Books.get (i));        }        Delete the third element        Books.remove (2);        SYSTEM.OUT.PRINTLN (books);        Determines the position of the specified element in the list collection: Output 1, indicating the second        System.out.println (Books.indexof (New String ("Ror Agile Development Best Practices"));//newly created object        Replace the second element with a new string Object        Books.set (1, new String ("Struts2 authoritative guide"));        SYSTEM.OUT.PRINTLN (books);        Sets the second element of the books collection (including) to the third element (not including) The Intercept subset        System.out.println (Books.sublist (1, 2));}    }

Program Run Result:

[Lightweight Java EE Enterprise Application Combat, Struts2 authoritative guide, based on the Java EE Ajax Collection]
Lightweight EE Enterprise Application combat
ROR Agile Development Best Practices
Struts2 Authoritative Guide
The Ajax treasure book based on Java EE
[Lightweight Java EE Enterprise Application Combat, ROR Agile Development Best practices, based on Java EE's AJAX Toolkit]
1
[Lightweight Java EE Enterprise Application Combat, Struts2 authoritative guide, based on the Java EE Ajax Collection]
[Struts2 authoritative Guide]

Program Description: The list collection can use the normal for loop to iterate through the collection elements. The list determines that two objects are equal as long as you return true by using the Equals method. The location of the "Ror Agile Development Best Practices" string, for example, creates a new string object, but the program still returns the location where the string object was created the first time. When you call the list's set (int index, Object Element) method to change the element at the specified index of the list collection, the specified index must be a valid index for the list collection.

Unlike set, which provides only one iterator () method, the list also provides an additional Listiteratro () method that returns an Listiterator object that inherits the iterator interface from the Listiterator interface. Provides a way to specifically manipulate the list.

The Listiterator interface adds the following method based on the iterator interface:

    • Boolean hasprevious (): Returns whether the iterator association collection has a previous element.
    • Object Previous (): Returns an element on the iterator.
    • void Add (): Inserts an element at the specified position.

Examples of programs:

public static void Main (string[] args)    {        string[] books = {            "Struts2 authoritative guide",            "lightweight Java EE Enterprise Application Combat"        };        List Booklist = new ArrayList ();        for (int i = 0; i < books.length; i++)        {            booklist.add (books[i]);        }        Listiterator lit = Booklist.listiterator ();        while (Lit.hasnext ())        {            System.out.println (Lit.next ());            Lit.add ("-------delimiter-------");        }        SYSTEM.OUT.PRINTLN ("reverse Iteration =========== under ==========");        while (Lit.hasprevious ())        {            System.out.println (lit.previous ());        }    }}

Program Run Result:

Struts2 Authoritative Guide
Lightweight EE Enterprise Application combat
========== below begins the reverse iteration ===========
-------delimiter-------
Lightweight EE Enterprise Application combat
-------delimiter-------
Struts2 Authoritative Guide

Program Description: When a list iterates through a collection of Listtterator, the next () method can be used for forward iterations, and the Add () method is used in the iterative process to append a new element to the next iteration of the element. The program also demonstrates the forward iteration.

2. ArrayList and vector implementation classes

The ArrayList and vector are the two typical implementations of the list class and fully support all the functions of the list interface described previously.

Both the ArrayList and the vector classes are array-based implementations of the list class, and they encapsulate a dynamically redistributed object[] array. Each ArrayList or vector object has a capacity property that represents the length of the object[] array they encapsulate. Capacity adds the number of elements and automatically increases them. When you add a large number of elements to the collection, you can use the Ensurecapacity method to increase the capacity at once. This can reduce the increase in redistribution times, which provides performance. The capacity size can also be specified at creation time, and the property defaults to 10.

ArrayList and vectors provide the following two ways to manipulate the capacity property:

    • void ensurecapacity (int mincapacity): Adds mincapacity to the capacity of the ArrayList or vector collection.
    • void TrimToSize (): Adjusts the capacity of the ArrayList or vector collection to the current size of the list. Programs can call this method to reduce the storage space of ArrayList or vector collection objects.

ArrayList and vector usage are almost the same, Vector is an ancient collection (from JDK1.0), at first Java has not yet provided a set of system framework, so the vector provides some method name is very long method: for example AddElement (Object obj), equivalent to the Add () method. Since JDK1.2, Java has provided a collection framework for the system, changing the vector to the Intern list interface as one of the list's internships, leading to a number of functional repetition methods in the vector. Vectors have many drawbacks, often using vectors to implement classes as little as possible.

ArrayList and Vector differences: ArrayList is thread insecure, when multiple threads access the same ArrayList collection, if more than one thread modifies the ArrayList collection, the program must manually guarantee the synchronization of the collection. The vector collection is thread-safe, and the wireless program guarantees the synchronization of the set. Because vectors are thread-safe, the performance of vectors is lower than that of ArrayList. In fact, vector implementation classes are also not recommended, even if the list collection is guaranteed to be thread-safe. Collections Tool class, you can turn a ArrayList into thread-safe.

Vector also provides a stack subclass that simulates the data structure of "stacks", which is usually referred to as a "last in, first Out" (LIFO) container. The last "push" element will be the first to be "pop" out of the stack. Like the rest of the collection in Java, the stack is an object, so you have to do the type conversion after you take the element out of the stack, unless you just use object with the action. So the Stack class provides several ways to do this:

    • Object Peek (): Returns the first element of the stack, but does not stack the element "Pop".
    • Object pop (): Returns the first element of the stack and pushes the element "pop" out of the stack.
    • void push (Object Item): Pushes an element "push" into the stack, and the last element in the "stack" is always at the top of the stack.

Examples of programs:

public class testvector{public    static void Main (string[] args)    {        Stack v = new Stack ();        Push three elements into the "stack"        v.push ("Struts2 authoritative guide") in turn;        V.push ("Light-weight EE enterprise Application Combat");        V.push ("Ror Agile Development Best Practices");        Output: [Struts2 authoritative guide, lightweight EE enterprise Application combat, ROR Agile Development Best Practices]        System.out.println (v);        Access the first element, but do not pop it out of the "stack", Output: ROR Agile Development Best Practices        System.out.println (V.peek ());        Still output: [Struts2 authoritative guide, lightweight EE enterprise Application combat, ROR Agile Development Best Practices]        System.out.println (v);        Pop out first element, output: ROR Agile Development Best Practices        System.out.println (V.pop ());        Still output: [Struts2 authoritative guide, lightweight EE Enterprise Application Combat]        System.out.println (v);}    }

Program Run Result:

[Struts2 authoritative guide, lightweight EE enterprise Application combat, ROR Agile development Best Practices]
ROR Agile Development Best Practices
[Struts2 authoritative guide, lightweight EE enterprise Application combat, ROR Agile development Best Practices]
ROR Agile Development Best Practices
[Struts2 authoritative guide, lightweight EE enterprise Application Combat]

3. LinkedList Realization Class

The list also has a LinkedList implementation, which is a list class based on a linked list, optimized for sequential access to the elements in the collection, especially when inserting and deleting elements at very fast speeds. Because LinkedList realizes the list interface, also implements the Deque interface (bidirectional queue), the Deque interface is a sub-interface of the queue interface, it represents a two-way list, the Deque interface defines some ways to operate the queue in two directions:

  • void AddFirst (Object e): Inserts the formulation element at the beginning of the bidirectional queue.
  • void AddLast (Object e): Inserts the formulation element at the end of the bidirectional queue.
  • Iterator descendingiterator (): Returns the iterator that corresponds to the bidirectional queue, which iterates over the elements in the queue in reverse order.
  • Object GetFirst (): Gets, but does not delete, the first element of a two-way queue.
  • Object getlast (): Gets, but does not delete, the last element of a two-way queue.
  • Boolean Offerfirst (Object e): Inserts the specified element at the beginning of the bidirectional queue.
  • Boolean offerlast (Object e): Inserts the specified element at the end of the bidirectional queue.
  • Object Peekfirst (): Gets, but does not delete, the first element of the bidirectional queue: Returns null if this double-ended queue is empty.
  • Object peeklast (): Gets, but does not delete, the last element of the bidirectional queue: Returns null if this double-ended queue is empty.
  • Object Pollfirst (): Gets and deletes the first element of the bidirectional queue: null if this double-ended queue is empty.
  • Object polllast (): Gets and deletes the last element of the bidirectional queue: null if this double-ended queue is empty.
  • Object pop (): POPs out the first element in the stack represented by the bidirectional queue.
  • void push (Object e): Pushes an element into the stack represented by the bidirectional queue (that is, the head of the bidirectional queue).
  • Object Removerfirst (): Gets and deletes the last element of the bidirectional queue.
  • Object Removefirstoccurrence (Object o): Removes the first occurrence of the two-way queue element O.
  • Object removelast (): Gets and deletes the last element of the bidirectional queue.
  • Object Removelastoccurrence (Object o): Removes the last occurrence of the two-way queue element O.

As can be seen from the above method, LinkedList can not only be used as a two-way queue, but also as a "stack" to use. At the same time, LinkedList implements the list interface, so it is also used as a list.

Examples of programs:

public class testlinkedlist{public    static void Main (string[] args)    {        LinkedList books = new LinkedList (); c3/>//the string element into the tail of the queue        books.offer ("Struts2 authoritative guide");        Put a string element into the stack        books.push ("Lightweight EE Enterprise Application Combat");        Adds a string element to the head of the queue        Books.offerfirst ("Ror Agile Development Best Practices");        for (int i = 0; i < books.size (); i++)        {            System.out.println (Books.get (i));        }        Accesses, does not delete the first element of a queue        System.out.println (Books.peekfirst ());        Access, do not delete the last element of the queue        System.out.println (Books.peeklast ());        The first element pops out of the queue        System.out.println (Books.pop ()) in a stack-out manner;        The output below will see that the first element in the queue is deleted        System.out.println (books);        Access, and delete the last element of the queue        System.out.println (Books.polllast ());        The following output will see that there is only one element left in the queue: Lightweight Java EE Enterprise Application Combat        System.out.println (books);}    }

Program Run Result:

ROR Agile Development Best Practices
Lightweight EE Enterprise Application combat
Struts2 Authoritative Guide
ROR Agile Development Best Practices
Struts2 Authoritative Guide
ROR Agile Development Best Practices
[Lightweight Java EE Enterprise application, Struts2 authoritative guide]
Struts2 Authoritative Guide
[Lightweight EE enterprise Application Combat]

Description: The program demonstrates the use of LinkedList as a two-way queue, stack, and list collection. LinkedList and ArrayList, vector implementation mechanism is completely different, ArrayList, vector in the form of arrays to save the elements in the collection, so random access to the collection element has better performance While the LinkedList internally saves the elements in the collection as a list, the performance is poor when the collection is randomly accessed, but it performs well when inserting and deleting elements (simply changing the address that the pointer refers to). Vector because of the implementation of the thread synchronization function, so the performance of the various aspects have been reduced.

A few suggestions for using the list collection:

    • If you need to traverse the list collection element, corresponding to the ArrayList, vector collection, you should use the random access method (get) to iterate over the collection elements, which makes the performance better. Corresponds to the LinkedList collection, an iterator (Iterator) should be used to iterate through the collection elements.
    • If you need to frequently perform insert, delete operations to change the LST collection size, you should use the LinkedList collection instead of ArrayList.
    • If more than one thread needs to access the elements in the list collection at the same time, consider using vector as a synchronous implementation.

Java Collection Framework Summary (4) Use of the--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.