Use of list, Map, Set, Collection, Stack, queue, etc. in Java

Source: Internet
Author: User
Tags set set

In Java, these things are more commonly used, although I do not use much, it is because of the use of a few, so I have been confused about their specific usage and the relationship between each other, now special as a single thing to summarize.

This article refers to the information:

1. The 11th chapter of Java Programming thought

2.http://blog.sina.com.cn/s/blog_a345a8960101k9vx.html

3.http://f51889920.iteye.com/blog/1884810

4.http://blog.csdn.net/speedme/article/details/22398395

5.http://www.tuicool.com/articles/qeezym

6.http://blog.csdn.net/hguisu/article/details/7644395

In the book "Java Programming thought", these things put in a chapter, in the 11th chapter. A lot of points to talk about, see for a while, look at the headache, but basically a lot of things can be understood, easier to comb.

First put a diagram in front, showing the relationship between their various collection classes, as follows:

Basic interface/class hierarchy of the Java collection framework

java.util.Collection [I]+--java.util.List [I]+--java.util.ArrayList [C]+--java.util.LinkedList [C]+--java.util.Vector [C]+--Java.util.Stack [C]+--Java.util.Set [I]+--Java.util.HashSet [C]+--Java.util.SortedSet [I]+--Java.util.TreeSet [C]java.util.map [I]+--Java.util.SortedMap [I]+--Java.util.TreeMap [C]+--java.util.Hashtable [C]+--Java.util.HashMap [C]+--Java.util.LinkedHashMap [C]+--Java.util.WeakHashMap [C] [I]: interface [C]: Class

So, why do you have a collection class?

Object-oriented language is the embodiment of things in the form of objects, in order to facilitate the operation of multiple objects, it is necessary to store the object, the collection class is a way to store multiple objects.

What is the difference between an array and a collection class?

The main difference is the variable length immutable problem. An array can store objects, but the lengths are fixed and immutable. The collection length is variable. Second, the array can store the base data type, and the collection can only store objects. One of the big advantages of collections is that you can store different types of objects. The array is not available.

Let's start with a summary of the following.

Collection interface

The collection interface is the most basic collection interface, which represents a set of object objects called collection elements. All types that implement the collection interface must provide two standard constructors: a parameterless constructor is used to create an empty collection, and a constructor with a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection, and a constructor allows the user to copy a collection. These are easier to understand.

1 New Arraylist<integer>(); 2 New Arraylist<integer> (Arrays.aslist (1,2,3,4,5));

Also note that there is no get () method in collection, to view or manipulate elements in collection can only be traversed, using the iterator () method, which can be used to access each element of the collection one at a time.

1 Iterator it = Collection.iterator (); // Get Iteration 2  while (It.hasnext ()) {3       Object obj = It.next (); // get the next element     4 }

The collection is divided into LST interface and set interface.

List interface

The list interface is an ordered collection that allows you to control exactly where each element is inserted, using an index to access the elements in the list, much like an array. And the list is allowed to have duplicate elements, of course, some list implementation class does not allow the existence of duplicate elements.

The list has the iterator () method, and the Listiterator method, which returns a Listiterator interface, which is more than the standard iterator interface, which allows adding, deleting, Sets the value of the element and the forward or backward traversal, and so on.

For example, there are several common classes under list: LinkedList, ArrayList, and Vector, and stack.

(1) ArrayList class: A variable-sized array is implemented. It allows all elements to be included, including NULL. Each ArrayList instance has a capacity, which is the size of the array used to store the elements, which can automatically increase as new elements are added, but the growth algorithm is not defined, and when a large number of elements are inserted, You can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.

(2) LinkedList class: Allows null elements, provides additional get,remove and insert methods, which allows LinkedList to be used as a stack, queue, or two-way queue. It can be inserted and removed in the middle of the list, which is more effective than ArrayList, but there is no ArrayList in random access. If multiple threads access a list at the same time, they must implement access synchronization on their own, and a workaround is to construct a synchronized list when the list is created:

List List = Collection.synchronizedlist (new LinkedList (...)) ;

(3) Vector class: Vectors are very similar to ArrayList, but vectors are synchronous, iterator created by vectors, although the iterator created by ArrayList are the same interface, but because vectors are synchronous, When a iterator is created and is being used, another thread changes the state of the vector (for example, adding or removing some elements), and when the iterator method is called, the concurrentmodificationexception is thrown. Therefore, the exception must be caught.

(4) Stack class: Inherit from Vector, implement a last-in-first-out stack. Provides several basic methods, push, pop, peak, empty, search and so on.

Summarize:

    • List: elements are ordered and elements can be duplicated. Because the collection system has an index.
      • ArrayList: The underlying data structure uses a data structure.
        • Queries are fast.
        • Additions and deletions are slightly slower.
        • Thread is out of sync.
        • The default length is 10 growth of 50%.
      • LinkedList: A linked list data structure used at the bottom.
        • The deletion speed is very fast.
        • The query is slightly slower.
      • Vector: The bottom layer is the array data structure. 1.0 appearance
        • Thread synchronization
        • Replaced by the ArrayList.
        • Length growth rate 100%.

Set interface

The set interface is inherited from collection, and it cannot contain duplicate elements . There is a maximum of one null element in set.

Because of this restriction of set, when using set set, it should be noted that: 1, a valid equals (Object) method is implemented for the implementation class of the elements in the set set. 2, for the set constructor, the passed-in collection parameter cannot contain duplicate elements.  Set there are several sets of classes, HashSet, SortedSet, TreeSet, with more is HashSet, the other two basic not commonly used, later slowly to supplement the knowledge, the following said HashSet. (1) HashSet, the underlying data structure hash table, supported by a hash table, does not guarantee the iteration order of the collection, in particular does not guarantee that the order is immutable, this class allows the use of NULL elements. The method by which HashSet guarantees element uniqueness is accomplished through the two methods of the element, hashcode and equals. If the hashcode value of the element is the same, the equals is not determined to be true.  If an element has a different hashcode value, equals is not called. (2) TreeSet: The bottom data structure type binary tree. Note: The add element must implement the comparable interface or specify the comparer when the instance TreeSet.You can sort the elements in the set collection. The basis for guaranteeing the uniqueness of the element: CompareTo method return 0; Map InterfaceMap Integrated Collection interface, map and collection are two different sets, collection is a collection of values (value), and map is a collection of key-value pairs (key,value).  Contains several main classes and interfaces: HashMap, Linkedmap, Weakhashmap, SortedMap, TreeMap, Hashtable, etc. (1) Hashtable inherits the map interface to implement a key-value mapped hash table. Any object that is not empty (non-null) can be either a key or a value. Add data using put (key, value), take out the data using get (key), the time overhead for these two basic operations is constant. (2)Weakhashmap class,Weakhashmap is an improved hashmap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally. Summary:If it involves operations such as stacks, queues, and so on, you should consider using the list, for quick insertions, for deleting elements, should use LinkedList, and if you need to quickly randomly access elements, you should use ArrayList.      if the program is in a single-threaded environment, or if access is done only in one thread, it is more efficient to consider non-synchronous classes, and if multiple threads may operate on a class at the same time, the synchronized classes should be used.      use Hashset,hashmap In addition to sorting, because they are more efficient treeset,treemap.      pay special attention to the operation of the hash table, and the object as key is to correctly replicate the Equals and Hashcode methods. The       container class can only hold object references (pointers to objects), rather than copy object information to a sequence of numbers. Once the object is placed inside the container, the object's type information is lost.      try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client-side code does not have to be changed. This is for abstract programming.   NOTE: 1, collection does not have a get () method to get an element. Elements can only be traversed by iterator (). 2. Set and collection have identical interfaces. 3, List, you can use the Get () method to remove one element at a time. Use numbers to select one of a bunch of objects, get (0) .... (Add/get) 4, the general use of ArrayList. Use LinkedList to construct stack stacks, queue queues. 5, map with put (K,V)/get (k), you can also use ContainsKey ()/containsvalue () to check if it contains a key/value.       hashmap will use the object's hashcode to quickly find the key.  6, the elements in the map, you can extract the key sequence, the value sequence alone. Use Keyset () to extract the key sequence and generate a set for all keys in the map. Use values () to extract the value sequence and generate a collection for all values in the map. Why a build set, a rawInto collection? That's because key is always unique, and value allows repetition.

Use of list, Map, Set, Collection, Stack, queue, etc. in Java

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.