How to choose Set, List, Map, array in Java development

Source: Internet
Author: User
Tags java util

---I don't produce code, I just code the porter.

In the Java util package there are two parent interfaces for all collections collection and map, their parent-child relationships:

           java.util        +collection This interface extends from--java.lang.iterab Le interface            +list interface               -arraylist class &N Bsp            -linkedlist class              -vector class   & nbsp This class is implemented in sync             +queue interface               + infrequently used, not in this form .            +set interface               +sortedset interface &nbsp ;                -treeset class              -hashset          +map interface          -hashmap class (in addition to not synchronizing and allowing the use of NULL keys/values, with Hashtable Roughly the same.)          -hashtable class This class is implemented synchronously and does not allow null key values           +SORTEDMAP interface &nbs P &nbSp          -treemap class    The following is a brief description of a number of interfaces and classes: First of all, we can not start with an array of arrays, Arrays java all Array is the most efficient way to "store and randomly access a series of objects."  1, high efficiency, but the capacity is fixed and cannot be changed dynamically. One drawback of array is that it is not possible to determine how many elements are actually stored, and length simply tells us the capacity of the array. There is a arrays class in  2 and Java that is specifically designed to manipulate arrays. Arrays has a set of static functions, Equals (): Compares two arrays for equality. Array has the same number of elements, and all corresponding element 22 is equal. Fill (): Fills the value into the array. Sort (): Used to sort the array. BinarySearch (): Looks for elements in a sorted array. System.arraycopy (): Copy of Array.   , Collection, map  If you do not know exactly how many objects are needed when writing a program, you need to use the Container class library if you want to automatically expand the capacity when there is insufficient space, and the array does not apply. The difference between  1, Collection, and Map   the number of elements stored in the container is different. collection type, with only one element per position. Map type, holding Key-value pair, like a small database. The purpose of the  2, Java Container class library is "Save Object", which is divided into two categories, the sub-class relationship  Collection       --list: The elements will be stored in a particular order. So the order taken out may be different from the order in which it is put.              --ArrayList/LinkedList/Vector       --set: cannot contain duplicates Elements              --HashSet/TreeSetMap       --HashMap    --hashtable   --treemap  Map----A pair of "key-value pairs" objects, that is, their elements are paired objects, the most typical application is a data dictionary, and there are a wide range of other applications. In addition, map can return a set of all its keys and all its values, or a set consisting of its key-value pairs, and can also extend a multidimensional map like an array, as long as each "value" of the key-value pairs in the map is a map. Collection.  collection 1. iterators   iterators are a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence.  Iterators are often referred to as "lightweight" objects because they are less expensive to create. The iterator functionality in Java is relatively simple and can only be moved one way: (1) using method iterator () requires the container to return a iterator. The first time you call Iterator's next () method, it returns the first element of a sequence. Note: The iterator () method is an Java.lang.Iterable interface that is inherited by collection.   (2) use Next () to get the next element in the sequence.   (3) use Hasnext () to check if there are elements in the sequence.   (4) use remove () to delete the newly returned element of the iterator.   Iterator is the simplest implementation of Java iterators, with more functionality for the listiterator of list design, which can traverse the list in two directions or insert and delete elements from a list.   2.List function methods   List (interface): Order is the most important feature of list; it ensures that elements are maintained in a specific order. The list adds a number of methods to collection, allowing you to insert and remove elements to the middle of the list (only recommended for linkedlist use). A list can generate Listiterator, which can be used to traverse a list in two directions or to insert and delete elements from the middle of a list.   ArrayList: A list implemented by an array. It allows for fast random access to elements, but it is slow to insert and remove elements into the list. Listiterator should only be used to traverse the ArrayList backward, rather than to insert and delete elements, as this is much larger than the linkedlist overhead.   LinkedList: List implemented by lists. To orderAccess is optimized to insert and delete the middle of the list with little overhead and random access is relatively slow (available ArrayList instead). It has methods AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), Removelast (), and these methods (not defined in any interface or base class) Enables LinkedList to be used as stacks, queues, and bidirectional queues.   3.Set Function method   Set (interface): Each element that is stored in set must be unique, which is different from list because Set does not save duplicate elements. The object that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained.   Hashset:hashset can quickly locate an element, and the object stored in HashSet must define HASHCODE ().   TreeSet: The set of the hold order, the bottom is the tree structure. Use it to extract ordered sequences from the set.   Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (inserted order). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.   HashSet uses a hash function to sort elements, which is specifically designed for quick queries; TreeSet The data structure of the red-black tree to sort the elements, Linkedhashset internally uses hashing to speed up the query, while maintaining the order of the elements using the linked list, Makes it seem that elements are saved in the order in which they are inserted. It is important to note that when generating your own classes, the set needs to maintain the order in which the elements are stored, so implement the comparable interface and define the CompareTo () method.  3, other features  *     LIST,SET,MAP will hold objects as object types. *     Collection, List, Set, map are all interfaces and cannot be instantiated. ArrayList, vectors, HashTable, and HashMap are inherited from them, and these can be instantiated. *     Vector container knows exactly what type of object it holds. Vectors do not perform boundary checks.    Collections collections isA helper class for the collection class. Provides a series of static methods for searching, sorting, threading, and so on for various collections. A class--arrays equivalent to a similar operation on an array. For example, Collections.max (Collection coll); Take the largest element in the Coll.        collections.sort (list list); Sort the elements in list   How do I choose? The differences between  1, container classes, and arrays, playable       *     container classes can only hold object references (pointers to objects), rather than copy object information to a sequence of numbers.       *     The object's type information is lost once the object is placed in the container.  2,      *     in various lists, the best practice is to ArrayList as the default choice. When inserting, deleting frequently, use LinkedList (); Vector is always slower than ArrayList, so try to avoid it.      *     in various sets, hashset is usually better than hashtree (INSERT, find). Use TreeSet only if you need to produce a sorted sequence. The only reason for the existence of  hashtree: the ability to maintain the ordering state of its elements.      *     in various maps    HASHMAP for quick Find.      *     When the number of elements is fixed, use array because the array is the highest efficiency.    Conclusion: The most common is arraylist,hashset,hashmap,array. Also, we will find a pattern, which is sorted by treexxx.    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, 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.     *     hashing          hash code is the transformation of the object's information into a unique int value, stored in an array. We all know that the array lookup speed is the fastest in all storage structures. So, you can speed up lookups.   When a collision occurs, let the array point to multiple values. That is, the array generates a table of cassia at each location.  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 Build collection? That's because key is always unique, and value allows repetition.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to choose Set, List, Map, array in Java development

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.