Java container class and traversal efficiency comparison __java

Source: Internet
Author: User
Java Container class and traversal efficiency comparison

1) Collection

Collection is the most basic set interface, and a collection represents a set of Object,java SDKs that do not provide a class that directly inherits from collection, and the Java SDK provides classes that inherit from collection "Sub-interfaces" such as list and set.

2) List

Elements are placed in the order in which they are inserted and are not rearranged.

3) Set

Do not answer love repeat element, it will use its own internal arrangement mechanism.

4) Map

A group of Key-value objects, that is, the holding of key-value pairs. There is no duplicate key in the map, it has its own internal arrangement mechanism.

5) Vector

Very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.

The purpose of the Java Container Class library is to "save Objects", which fall into two categories:

Collection----A set of independent elements, which are usually subject to some sort of rule. The list must maintain an element-specific order, and set cannot have duplicate elements.

MAP----A pair of "key-value pairs" objects, whose elements are pairs of objects, the most typical application is the data dictionary, and there are other extensive applications. In addition, a map can return a set of all its keys and all its values, or a set consisting of its key pairs, and can also extend the multidimensional map as an array, so long as each "value" of the key value pair in the map is a map collection.

1. Iterators

An iterator is a design pattern that is an object that traverses and selects objects in a sequence, and developers do not need to understand the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because the cost of creating them is small.

The iterator function in Java is simpler and can only be moved in one Direction:

(1) using the method iterator () requires the container to return a iterator. The first time the iterator next () method is invoked, it returns the first element of the sequence.

(2) Use Next () to get the next element in the sequence.

(3) Use Hasnext () to check if there are any elements in the sequence.

(4) Remove the newly returned elements of the iterator using remove ().

Iterator is the simplest implementation of the Java iterator, with more functionality for the list design listiterator, which can traverse the list in two directions or insert and delete elements from the list.

2.List method of function

List (interface)

The order is the most important feature of the list, and it ensures that the element-specific order is maintained. List adds a number of methods to collection that allow you to insert and remove elements in the middle of the list (only recommended for linkedlist use). A list can generate Listiterator, using it to traverse the list in two directions, or to insert and delete elements from the list.

ArrayList

The list implemented by the array. It allows fast random access to elements, but it is slow to insert and remove elements in the middle of the list. Instead of inserting and deleting elements, listiterator should only be used to traverse the ArrayList backwards, because it is much larger than the linkedlist overhead.

LinkedList

Sequential access is optimized to insert and delete in the middle of the list with little overhead, and random access is relatively slow (available ArrayList instead). It has method AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), Removelast (), these methods (not defined in any interface or base class) Enables LinkedList to be used as stacks, queues, and bidirectional queues.

3.Set method of function

Set (interface)

Each element that is stored in the set must be unique because the set does not save the repeating element. The object that joins the set must define the Equals () method to ensure the uniqueness of the object. Set has exactly the same interface as collection. The set interface does not guarantee the order of elements to be maintained.

HashSet

A set designed for quick lookup. The object that is stored in the HashSet must define HASHCODE ().

TreeSet

The set in order, the bottom is the tree structure. Use it to extract ordered sequences from set.

Linkedhashset

has a HashSet query speed and internally uses a linked list to maintain the order of elements (in the order of insertion). So when you use iterators to traverse set, the results are displayed in the order in which the elements are inserted.

HashSet uses hash functions to sort elements, which are specifically designed for quick queries; TreeSet The data structure of the red-black tree to sort elements; Linkedhashset uses hashes to speed up query speed, while using linked lists to maintain the order of elements, Makes it appear that the elements are saved in the order in which they were inserted. Note that when building your own class, the set needs to maintain the order in which the elements are stored, so implement the comparable interface and define the CompareTo () method.  

Test Program

Import java.util.ArrayList;
Import Java.util.Iterator;

Import java.util.List;

public class Listtest {public static void main (String args[]) {List lists = new ArrayList ();

for (Long i=0l;i<1000000l;i++) {lists.add (i);}
Long oneok = Onemethod (lists);
Long Twook = Twomethod (lists);
Long Threeok = Threemethod (lists);

Long Fourok = Fourmethod (lists);
System.out.println ("one:" + oneok);
System.out.println ("two:" + Twook);
System.out.println ("Three:" + threeok);

System.out.println ("Four:" + Fourok); public static Long Onemethod (listlists) {Long Timestart = System.currenttimemillis (), for (int i=0;i System.out.println
(Lists.get (i));

Long timestop = System.currenttimemillis ();
return timestop-timestart; public static Long Twomethod (listlists) {Long Timestart = System.currenttimemillis (), for (Long string:lists) {Syste
M.out.println (string);

Long timestop = System.currenttimemillis ();
return timestop-timestart; public static Long Threemethod (listlists) {long timestArt = System.currenttimemillis ();
Iterator it = Lists.iterator ();
while (It.hasnext ()) {System.out.println (It.next ());}

Long timestop = System.currenttimemillis ();
return timestop-timestart; public static Long Fourmethod (listlists) {Long Timestart = System.currenttimemillis (); for (Iterator i = Lists.iterator (); I.hasnext ();)
{System.out.println (I.next ());}

Long timestop = System.currenttimemillis ();
return timestop-timestart; }
}

Test Results

one:14109 two:14000 three:15141 four:14297

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.