Java Collection Connection stack queue and some common

Source: Internet
Author: User
Tags addall set set

Collection Family Map

---| Collection: Single-column collection           ---| List: With storage order, repeatable              ---| ArrayList:     array implementation, Find Fast, and delete slow                                        ---| LinkedList:    linked list implementation, delete fast, find slow   implementation of the stack queue                                     ---| Vector:    Same principle as ArrayList, but thread-safe, slightly less efficient            ---| Stuck Class            ---| Set: No storage order, non-repeatable              ---| HashSet  thread is not secure and access speed is fast. The bottom layer is a hash table implementation of the              ---| TreeSet  
 ---| Linkedhashmap and additions to the map collection to improve efficiency
Connection

Collection is the most basic set interface, and a Collection represents a set of Object, the Collection element ( Elements).

Some Collection allow the same elements while others do not. Some can sort and others can't.

The Java SDK does not provide classes that inherit directly from Collection, and the Java SDK provides classes that inherit from Collection "Subinterfaces " such as List and set.

All classes that implement the Collection interface must provide two standard constructors:

Parameterless constructors are used to create an empty Collection,

A constructor that has a Collection parameter is used to create a new Collection,

This new Collection has the same elements as the incoming Collection.

The latter constructor allows the user to copy a Collection.

Connection common methods. Added:       1:add () to   store the specified object in the container the                   argument type of the Add method is an object that is easy to receive any object       2:addall () to add the elements in the specified collection to the call method and delete the collection:       3:remove () Removes the specified object from the collection       4:removeall () removes the element from the specified collection modify       5:clear () empties all elements in the collection to determine       whether the collection is empty or not ()       7:contains () determines whether the collection contains the specified object                 8:containsall () determines whether the collection contains the specified collection         using Equals () to determine whether two objects are equal gets:   9:int size ()    
List
List-specific Method 1: Add        void Add (int index, E Element) specify location add Element                    boolean addall (int index, Collection c) Specify location Add collection  2: Remove e Remove (int index) deletes the specified position element 3: Modify        e set (int index, e Element)    returns the element in the collection that needs to be replaced 4: find:        E get (int index)             Note: indexoutofboundsexception        int indexOf (object o)         //Cannot find return-1        lastIndexOf (Object o) 5: Find subset         List  <E> sublist (int fromIndex, int toindex)//Toindex not included   

LinkedList Non-synchronous
Link list implementation, delete fast, find slow LinkedList unique Method 1: Method Introduction AddFirst (E E) addlast (e) GetFirst () GetLast () Removefirst () removelast () If there are no elements in the collection, Get or delete elements thrown: NoSuchElementException2: Data structure LinkedList list = new LinkedList (); 1: Stack (1.6)         advanced after        push ()    into the stack        Pop ()     out     of stack 2: Queue (double-ended queue 1.5)        advanced first Out offer        ()      Queued        poll ()    outbound peek ()       gets the header element of the queue, but does not delete the PEEKFI RST ()  gets the header element of the queue, but does not delete peeklast ()   gets the last element of the queue but does not delete 3: Returns an Iterator object in reverse order      descendingiterator ()   Returns an iterator object in reverse order Note: Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list:list list = collections.synchronizedlist (new LinkedList (...) when the list is created. ;
ArrayList Non-synchronous
Array implementation, Find Fast, and delete slowly
Vector Synchronization
Vector: Describes a thread-safe ArrayList. ArrayList: Single thread efficiency high vector    : multithreading safe, so inefficient vector-specific method void AddElement (E obj)  at the end of the collection add element E elementat (int index) returns the specified angle The underlying element enumeration elements ()  returns all elements in the collection, encapsulated into the enumeration object enumeration interface:  Boolean hasmoreelements ()           Tests whether this enumeration contains more elements.   E nextelement ()           returns the next element of this enumeration if there is at least one element that can be supplied by this enumeration object. The Iterator created by the vector, although the same interface as the Iterator created by ArrayList, but because the vector is synchronous, when a Iterator is created and is being used, another thread changes the state of the vector (for example, Tim Add or remove some elements), the Iterator method will be called when the concurrentmodificationexception is thrown, so the exception must be caught.

Stack class

Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the Vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created as an empty stack.
iterators
Each collection class may return different Iterator specific types, but they all implement the Iterator interface, so we don't need to care what kind of Iterator it is, it just needs to get the Iterator interface, which is the benefit of the interface, the power of object-oriented. Iterator it = List.iterator (); Itreator    The interface is a collection of iterator interface classes that define common iterative methods    1:boolean Hasnext ()                         Determine whether there are elements in the collection, Returns true if there are elements that can iterate.    2:e Next ()                          returns the next element of the iteration, note: If there is no next element, calling the next element throws Nosuchelementexception    3:void remove ()                        Removes the last element returned by an iterator from the collection that the iterator points to (optional action).

List-specific iterators Listiterator

Listiterator<E>  listiterator ()---| Iterator        hasnext ()        next ()        remove ()       ------| Listiterator iterator sub-interface list exclusive iterator                  Add (e E)    inserts the specified element into the list (optional action). The element is inserted directly into the front of the next element returned by next (if any)                  void set (E o)   replaces the last element returned by next or previous with the specified element                  hasprevious ()    Returns true if the list iterator has more than one element in the reverse loop.                  Previous ()       returns the previous element in a list. 

Set
Does not contain duplicate elements Hashsettreesetlinkedhashset
Map
Note: Set elements cannot be duplicated, MAP keys cannot be duplicated, and if a repeating element is stored, duplicate elements cannot be stored in the Add method to returnfalsethe MAP's repeat master overrides the old key and returns the old value. 1, add:1, V put (K key, V value) (can be the same key value, but the added value will overwrite the previous, the return value is the previous one, if not, return null) 2, Putall (map<?extendsK?extendsV>m) copies all mappings from the specified mappings into this map (optional operation). 2, delete1, remove () to delete the associated object, specify the Key object2, Clear () empties the collection object3, Get1: Value get (key), which can be used to determine if a key exists. Null is returned when the specified key does not exist. 3, Judgment:1.BooleanisEmpty () length of 0 returns true otherwise false2.BooleanContainsKey (Object key) determines whether the specified key is contained in the collection3.BooleanContainsvalue (Object value) determines whether the specified value is contained in the collection4, Length: Int size () method to traverse map1, all keys in the map collection are fetched into the set set. Set<K>KeySet () returns the set set of all key objects and gets the value corresponding to the key by the Get method. 2, values (), to get all the values. Collection<V>values () cannot get to the key object3, Map.entry object recommended use Focus Set<Map.Entry<k,v>>EntrySet () packages the key-value mappings in the Map collection into an object Map.entry objects get their keys and values through the Getkey,getvalue of the Map.entry object. //Get method://The first way: Using keyset//need to get key and value separately, no object-oriented thought//set<k> KeySet () returns the set set of all key objectsSet<integer> KS =Map.keyset (); Iterator<Integer> it =Ks.iterator ();  while(It.hasnext ()) {Integer key=It.next (); String value=Map.get (key); System.out.println ("key=" + key + "value=" +value); }        //The second way://get all values through values, cannot get to the key object//collection<v> values ()Collection<string> vs =map.values (); Iterator<String> it1 =Vs.iterator ();  while(It1.hasnext ()) {String value=It1.next (); System.out.println ("Value=" +value); }        //The Third Way: Map.entry object recommended use of focus//set<map.entry<k,v>> EntrySet ()//The returned Map.entry object's set collection Map.entry contains the key and the value objectSet<map.entry<integer, string>> es =Map.entryset (); Iterator<map.entry<integer, string>> it2 =Es.iterator ();  while(It2.hasnext ()) {//returns the Map.entry object that encapsulates the key and value objectsMap.entry<integer, string> en =It2.next (); //gets the key and value objects encapsulated in the Map.entry objectInteger key =En.getkey (); String value=En.getvalue (); System.out.println ("key=" + key + "value=" +value); }

HashMap

The underlying is a hash table data structure that the thread is not synchronized and can be stored in a null key, null value. to guarantee the uniqueness of the key, you need to overwrite the Hashcode method, and the equals method.

map<string, integer > map1 = new hashmap<string, Integer > ();

Hashmap<person, string> HM = new Hashmap<person, string> ();

TreeMap

Custom element Ordering

class Implements Comparator<person> {    @Override    publicint  compare (person P1, person p2) {        if (P1.getage () > p2.getage ()) {            return -1;         Else if (P1.getage () < p2.getage ()) {            return 1;        }         return p1.getname (). CompareTo (P2.getname ());}    }

Java Collection Connection stack queue and some common

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.