Java depth-Deep understanding of Java collection __java

Source: Internet
Author: User
Tags addall comparable int size set set
Collection

The collection class is stored in the Java.util package.

There are 3 main types of collections: Set (Set), list (lists include queue), and map (map).

Collection:collection is the basic interface of a set, the most basic interface of List, Set, and queue.

Iterator: iterators that iterate through the data in the collection through iterators

Map: is the underlying interface of the mapping table



List ordered Collection

The Java list is a very common type of data. List is an orderly collection. The Java list has three implementation classes: ArrayList, Vector, and LinkedList, respectively.

ArrayList: ArrayList is the most commonly used list implementation class, which is implemented internally through arrays, allowing for fast random access to elements. The disadvantage of an array is that there can be no spacing between each element, and when the array size is not satisfied, the storage capacity needs to be increased, so that the data already in the array is copied into the new storage space. When inserting or deleting elements from the middle of the ArrayList, it is necessary to copy, move, and cost the array. Therefore, it is suitable for random lookup and traversal, unsuitable for inserting and deleting.

Vector: Vectors, like ArrayList, are also implemented through arrays, except that it supports thread synchronization, that is, only one thread at a time can write vectors, avoiding inconsistencies caused by multithreading being written at the same time, but achieving synchronization requires a high cost, so Accessing it is slower than accessing ArrayList.

LinkedList: LinkedList is a linked list structure to store data, it is very suitable for dynamic insertion and deletion of data, random access and traversal speed is relatively slow. In addition, he provides methods that are not defined in the list interface, specifically for manipulating headers and footer elements, and can be used as stacks, queues, and bidirectional queues.


Description:

1. ArrayList when memory is not enough, the default is to expand 50% + 1, vector is the default extension of 1 time times.

2. Vectors are thread-safe, but in most cases vectors are not used because thread safety requires a greater overhead.

3. General use of ArrayList and LinkedList ratio

4. For random access get and set,arraylist feel better than LinkedList because linkedlist to move the pointer

5. Add and Remove,linedlist are more advantageous for new and delete operations because ArrayList want to move data


ArrayList

ArrayList is the most commonly used list implementation class. The interior of the ArrayList is implemented through an array. So it is only suitable for traversal or random lookup.

Common interfaces:

List.add (int index,e Element) adds the data to the specified location
list.add (E Element) to add the specified element to the end of this list.
List.addall (collection<. extendse> c) Adds all the elements in the Collection to the end of this list according to the order of the elements returned by the specified Collection iterator.
list.addall (int index,collection<? extendse> c) Inserts all the elements in the specified Collection into this list, starting at the specified location.
list.clear () Removes all elements from this list.
list.set (int index,e element)  replaces the element at the specified position in this list with the specified element.
list.get (int index) returns the element at the specified position in this list.
list.size () View the total number of elements
List.contains () contains


Example:

public class Test2 {/** * entry function * @param args/public static void main (string[] args) throws exc

        eption {/* Initializes an array */list<integer> List = new arraylist<integer> ();
        /* NEW Data * * for (int j = 0; J < 5; j) {List.add (j);

        ////* Total length/System.out.println (List.size ());

        /* Delete a data key=1 * * LIST.REMOVE (1); /* Traverse * (int i = 0; i < list.size (); i++) {System.out.println ("for:" + list.get (i));
        Get value}/* Combine a set/* list<integer> List2 = new arraylist<integer> ();
        List2.add (99);
        List2.add (100);

        List.addall (LIST2);
        /* Traverse 2 */Iterator it = List.iterator (); while (It.hasnext ()) {System.out.println ("iterator:" + it.next ());
        Gets the value}/* whether contains/if (List.contains (2)) {System.out.println ("included");
}
        /* Empty list */List.clear (); Clear entire List}}


LinkedList

is to store objects in the structure of a linked list, dynamic additions and deletions are quick, but traversal is slow and there is no operation of get () and cannot be positioned individually. To be blunt, ArrayList is a sequential storage structure, and LinkedList is a linked-list storage structure.


Common interface:

Public LinkedList () generates an empty linked list public
LinkedList (Collection col):  copy Constructor Public
boolean Add (Object Element) add Element public boolean
Add (int index, Object Element) public boolean
AddFirst (object Element)
public Boolean AddLast (Object Element)
List.addall (collection<? extendse> c) Converts the Collection by the order of the elements returned by the iterator of the specified Collection Adds all of the elements in the to the end of this list.
List.removefirst ();
List.removelast ();
List.clear ();
List.sublist (2, 5). Clear ();
List.remove ("2"); #删除特定元素
list<string> myList = new arraylist<string> (List);  #转ArrayList
Llist.indexof ("2") to  find the element position
Llist.lastindexof ("2");
Llist.set (3, "replaced");
Llist.contains ("4"); Confirm that there is


Example:

public class Test2 {/** * entry function * @param args/public static void main (string[] args) throws exc
        eption {/* generates a linkedlist/linkedlist<string> list = new linkedlist<string> ();
        List.add ("a");
        List.add ("B");
        List.add ("C");

        List.add ("D");
        /* List size */int size = List.size ();

        SYSTEM.OUT.PRINTLN (size);
        /* Get the first and last element */String: List.getfirst ();
        String last = List.getlast ();

        System.out.println ("A:" + "+" + "Last:" + last);
        /* Add the first and last element * * * * List.addfirst ("a");
        List.addlast ("last");

        SYSTEM.OUT.PRINTLN ("List content:" + list);
        /* Remove the last and first */List.removefirst ();
        List.removelast ();

        SYSTEM.OUT.PRINTLN ("List content:" + list);
        /* Delete the specific element */List.remove ("B");

        SYSTEM.OUT.PRINTLN ("List content:" + list); /* Find element position */int i = List.indexof ("C");

        System.out.println ("Position:" + i);
        /* contains an element */if (List.contains ("C")) {System.out.println ("included");
        /* Set an element/* List.set (1, "Sadsad");

        SYSTEM.OUT.PRINTLN ("List content:" + list);
        /* to ArrayList * * list<string> alist = new arraylist<string> (List);
        for (String s:alist) {System.out.println ("s =" + s);
        /* Convert to Array/string[] my = List.toarray (New String[list.size ()));
        for (int j = 0; J < My.length; J + +) {System.out.println (my[j]);
        /* Assembly list */linkedlist<string> List2 = new linkedlist<string> ();
        List.add ("ddd");
        List.add ("111");
        List.addall (LIST2);

        SYSTEM.OUT.PRINTLN ("List content:" + list);
        /* Traverse * * iterator lit = list.iterator ();
        while (Lit.hasnext ()) {System.out.println (Lit.next ());
      } * * Clear/  List.clear ();
    SYSTEM.OUT.PRINTLN ("List content:" + list); }
}


Set Set

Several features of Set set:

1. Set collection does not allow duplicate data

2. Allow elements that contain values to be null, but can have only one null element.


TreeSet

Several characteristics of TreeSet:

1. There can be no duplicate elements in the TreeSet;

2. TreeSet has a sort function, and the default is to arrange by natural sort

3. elements in TreeSet must implement the comparable interface and override the CompareTo () method , TreeSet determine whether the elements are duplicated, and determine the order of the elements by this method

4. Based on TREEMAP implementation

Example:

There can be no duplicate elements in the public class Test {public static void main (string[] agrs) {/** * treeset; The set has a sort function; * Elements in TreeSet must implement the comparable interface and override the CompareTo () method, treeset determine whether the elements are duplicated, and determine the order of the elements by this method * If you are customizing a class, you can

        To achieve the comparable interface, and implement CompareTo, complete the custom to heavy/treeset<string> set = new treeset<string> ();
        * * Add Data * * SET.ADD ("abc");
        Set.add ("xyz");
        Set.add ("BCD");

        Set.add ("BAC");
        treeset<string> Set2 = new treeset<string> ();
        Set2.add ("TTT");
        Set2.add ("zzz");

        Set2.add ("zzz");

        /* Add a set * * Set.addall (SET2);
        Iterator it = Set.iterator ();
        while (It.hasnext ()) {System.out.println (It.next ());
        /* Get the first element */String: Set.first ();

        System.out.println ("A:" + a);
        /* Get the last element */String at the end = Set.last ();

    System.out.println ("Last:" + last);    /* contains an element */if (Set2.contains ("TTT")) {System.out.println ("contains:true");
        }/* To determine if the null/if (Set.isempty ()) {System.out.println ("null");

        /* Number of elements/* SYSTEM.OUT.PRINTLN ("Number of elements:" + set.size ());

    * * Empty Set/Set.clear (); }
}


HashSet

Several characteristics of HashSet:

1. There can be no duplicate elements in the hashset;

2. The hashset is disordered.

3. HashSet is also based on HASHMAP implementation

Example:

There can be no duplicate elements in the public class Test {public static void main (string[] agrs) {/** * hashset; * Hash

        Set is unordered * HashSet is also based on HASHMAP implementation */set<string> Set = new hashset<string> ();
        * * Add Data * * SET.ADD ("abc");
        Set.add ("xyz");
        Set.add ("BCD");

        Set.add ("BAC");
        set<string> Set2 = new hashset<string> ();
        Set2.add ("TTT");
        Set2.add ("zzz");

        Set2.add ("zzz");

        /* Add a set * * Set.addall (SET2);
        /* To determine whether the null/if (Set.isempty ()) {System.out.println ("null");

        /* Number of elements/* SYSTEM.OUT.PRINTLN ("Number of elements:" + set.size ());

        /* Remove element */set.remove ("zzz");
        Iterator it = Set.iterator ();
        while (It.hasnext ()) {System.out.println (It.next ());
        }/* contains an element */if (Set2.contains ("TTT")) {System.out.println ("contains:true");

     }   * * Empty Set/Set.clear (); }
}


Map

The map sets are mainly: Hashmap,treemap


HashMap

HashMap Features:

1. HashMap is a unordered hash table;

2. HashMap through the hash algorithm to determine the storage location

3. The underlying implementation is a hash table

Example:

public class Test {public static void main (string[] agrs) {/** * HashMap is a unordered hash table; * Hash

        Map through the hash algorithm to determine the storage location/hashmap<string, string> map = new hashmap<string, string> ();
        /* Fill Data * * map.put ("username", "initphp");

        Map.put ("Age", "100");

        /* Get the number of elements * * SYSTEM.OUT.PRINTLN (Map.size ());
        * All/* hashmap<string, string> map2 = new hashmap<string, string> ();
        Map2.put ("UserName2", "Initphp2");
        Map2.put ("Age2", "1002");

        Map.putall (MAP2);
        /* Through key traversal hashmap * * iterator it = Map.keyset (). iterator ();
            while (It.hasnext ()) {string key = (String) it.next ();
        System.out.println ("key:" + key + "value:" + map.get (key));
        }/* contains a key/if (Map.containskey ("Age")) {System.out.println ("contains a key"); }/* To determine whether NULL/if (Map.isempty ()) {
            System.out.println ("Empty");

        } * * Delete an element/Map.Remove ("age");

    /* Empty Map Table */map.clear (); }
}

TreeMap

Characteristics of TreeMap:

1. It is suitable for traversing key (key) in natural order or custom order.

2. The bottom is two fork tree

3. Provide CompareTo, you can define the sorting method

public class Test {    public static void Main (string[] agrs) {      &nbsp ; /**          * 1.
Applies to traversing keys (key) in a natural order or in a custom order.          * 2. The bottom is a two-fork tree          * 3. Provides CompareTo, can define sorting method         /*       

  treemap<string, string> map = new treemap<string, string> ();        /* Fill data */        Map.put ("username")
, "initphp");

        map.put ("Age", "100");        /* Get the number of elements * *        

System.out.println (Map.size ());         * Put all */        treemap< String, string> map2 = new treemap<string, STring> ();
        map2.put ("UserName2", "Initphp2");
        map2.put ("Age2", "1002");

        Map.putall (MAP2);        //* Through key traversal HashMap, is an ordered */       
Iterator it = Map.keyset (). iterator ();         while (It.hasnext ()) {        
    string key = (string) it.next ();             System.out.println ("key:" + key + "value:" +
Map.get (key));        }        /* contains a key */         if (Map.containskey ("Age")) {        
    System.out.println ("whether to include a key");        } &NBSP;&NBsp;     /* To determine if NULL/        if (Map.isempty ()) { &
nbsp;          System.out.println ("Empty");        }         String a = Map.firstkey (
);
        String last = Map.lastkey ();
        System.out.println ("A:" + a);

        System.out.println ("last" + last);        /* Delete an element */        Map.Remove ("Age"

);

       /* Empty map Table */        map.clear ();
    }}


Queue

LinkedList is a queue.

The common queue are: Priorityqueue, Concurrentlinkedqueue, Arrayblockingqueue, Linkedblockingqueue, Priorityblockingqueue


Priorityqueue

Example:

public class Test {public static void main (string[] agrs) {/* generates a linkedlist/* priorityqueue<s
        tring> queue = new priorityqueue<string> ();
        Queue.add ("a");
        Queue.add ("B");
        Queue.add ("C");

        Queue.add ("D");
        /* Queue Size */int size = Queue.size ();

        SYSTEM.OUT.PRINTLN (size);
        /* Delete the specific element */Queue.remove ("B");

        SYSTEM.OUT.PRINTLN ("List content:" + queue);
        /* contains an element */if (Queue.contains ("C")) {System.out.println ("included");
        /* Assembly list */priorityqueue<string> queue2 = new priorityqueue<string> ();
        Queue2.add ("ddd");
        Queue2.add ("111");
        Queue.addall (queue2);

        SYSTEM.OUT.PRINTLN ("List content:" + queue);
        /* Traverse * * iterator lit = queue.iterator ();
        while (Lit.hasnext ()) {System.out.println (Lit.next ()); /* * Eject an element from the header of the queue */string string = QuEue.poll ();
        System.out.println ("Poll:" + string);
        string = Queue.poll ();

        System.out.println ("Poll:" + string);
        /* Eject an element from the tail head/string = Queue.peek ();

        System.out.println ("Peek:" + string);

        SYSTEM.OUT.PRINTLN ("List content:" + queue);
        * * Clear/queue.clear ();
    SYSTEM.OUT.PRINTLN ("List content:" + queue); }
}







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.