A detailed description of data structures in Java

Source: Internet
Author: User
Tags addall set set

  Linear table, linked list, hash table is a common data structure, in Java development, the JDK has provided us with a series of corresponding classes to implement the basic data structure. These classes are all in the Java.util package. This article attempts to explain to the reader the functions of each class and how to use them correctly through a simple description.

Collection

├list

│├linkedlist

│├arraylist

│└vector

│└stack

└set

Map

├hashtable

├hashmap

└weakhashmap

Collection interface

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, such as list and set.

  All classes 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 elements as the incoming collection. The latter constructor allows the user to copy a collection.

How do I traverse every element in the collection? Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that uses the iteration to access each element of the collection one at a time. Typical usage is as follows:

// get an iteration child    while (It.hasnext ()) {      //  Get Next element   }

The two interfaces that are derived from the collection interface are list and set.

Main methods:

  • Boolean Add (Object o) to the collection
  • Boolean Remove (object o) deletes the specified object
  • int size() returns the number of elements in the current collection
  • Boolean contains(object O) finds whether the specified object is in the collection
  • Boolean isEmpty() determines whether the collection is empty
  • Iterator Iterator() returns an iterator
  • Boolean Containsall(Collection C) finds whether the collection has elements in the collection C
  • Boolean AddAll(Collection c) adds all elements of collection C to the collection
  • void Clear() deletes all elements in the collection
  • void RemoveAll(Collection c) removes elements from the collection that are also in the C collection
  • void Retainall(Collection c) removes elements not contained in collection C from the collection

List interface

  The list is an ordered collection, using this interface to precisely control where each element is inserted . The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of Java .

Unlike the set mentioned below , the list allows the same elements .

In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a Listiterator () method that returns a Listiterator interface , compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.

The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

Main methods:

    • void add (int index,object Element) Adds an object at the specified position
    • Boolean addall (int index,collection c) adds the elements of the collection C to the specified location
    • Object Get (int index) returns the element at the specified position in the list
    • int indexOf (Object o) returns the position of the first occurrence of element o
    • Object removeint (int index) deletes the element at the specified position
    • The Object set (int index,object element) replaces the element on position index with element elements, returning the substituted element

LinkedList class

The LinkedList implements a list interface that allows null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque).

Note 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 when the list is created:

List List = Collections.synchronizedlist (new

ArrayList class

  ArrayList implements a variable-size array. It allows all elements, including null. ArrayList is not synchronized.

Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time.

Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity automatically increases as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency .

Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

Main methods:

    • boolean Add (Object o) adds the specified element to the end of the list
    • boolean Add (int index,object element) Specify the position in the list add the specified element
    • boolean AddAll (Collection c) adds the specified collection to the end of the list
    • boolean addall (int index,collection c) Specify a location in the list join the specified collection
    • boolean Clear () Delete all elements in the list
    • boolean Clone () returns a copy of the list instance
    • boolean contains (Object o) to determine if the list contains elements
    • boolean ensurecapacity (int m) increases the capacity of the list and, if necessary, can accommodate m-Elements
    • object get (int index) returns the element at the specified position in the list
    • int indexOf (Object elem) finds the subscript for the specified element in the list
    • int size () returns the number of elements in the current list

Vector class

  vectors are very similar to ArrayList, but vectors are synchronous .

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 , adding or removing some elements), when calling iterator's method throws Concurrentmodificationexception, 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.

Set interface

  Set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.

Obviously, the constructor of a set has a constraint that the passed-in collection parameter cannot contain duplicate elements .

Note: Variable objects (Mutable object) must be handled with care. if a mutable element in a set changes its state, causing Object.Equals (Object) =true will cause some problems .

Map interface

Note that map does not inherit the collection interface, and map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value. The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.

Map is used to hold data that has a mapping relationship, and the map holds two sets of data: Key and value, all of which can make any reference type of data, but key cannot be duplicated. Therefore, the corresponding value can be taken out by the specified key. The map interface defines the following common methods:

  • Boolean equals (object o) Comparison object
  • Boolean remove (Object o)
  • Put (Object key,object value) add key and value
  • 1, void clear(): Delete the map in the key value pair.

    2. Boolean containskey(Object key): Queries whether the map contains the specified key and returns True if it is included.

    3. Boolean containsvalue(Object value): Queries whether the map contains the specified value and returns True if it is included.

    4. Set entryset(): returns the set set of key-value pairs contained in the map, each of which is a Map.entry object (entry is the inner class of the map).

    5, Object get (Object key): Returns the value corresponding to the specified key, or null if the map does not contain a key.

    6. Boolean isEmpty(): Query if map is empty and returns true if NULL.

    7. Set KeySet (): Returns the set set of all keys in the map .

    8, Object put (object Key,object value): Add a key-value pair, if there is already an identical key value, the new key-value pair overrides the old key-value pair.

    9. void Putall (map m): Copies the key-value pairs from the specified map to the map .

    10, Object remove (Object key): Removes the key value pair corresponding to the specified key, returns the value that can be associated, or null if key does not exist.

    11, int size (): Returns the number of key-value pairs in the map.

    12. Collection VALUES (): Returns the Collection of all value components in the map.

    The map contains an inner class: Entry. The class encapsulates a key-value pair , which contains three methods:

    1, Object GetKey (): Returns the key value contained in the entry.

    2, Object Getvaleu (): Returns the value contained in the entry.

    3, Object SetValue (V value): Sets the value contained in the entry and returns the value of the new setting.

Hashtable class

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.

The Hashtable adjusts performance through the initial capacity and load factor two parameters. Normally the default load factor 0.75 is a good way to achieve a balanced time and space. Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations like get and put.

A simple example of using Hashtable is to put the three-to-one in the Hashtable, with their key being "single", "Two", "three":

New Hashtable ();   New Integer (1));   New Integer (2));   New Integer (3

To take out a number, say 2, with the corresponding key:

Integer n = (integer) numbers. Get ("both");

Because an object that is a key will determine the position of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods. The hashcode and Equals methods inherit from the root class object, and if you use a custom class as key, be quite careful, as defined by the hash function, if two objects are the same, i.e. obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode may not be different, if the hashcode of two different objects is the same, this phenomenon is called a conflict, the conflict causes the time overhead of manipulating the hash table, so define the hashcode () as much as possible. method to speed up the operation of the hash table.

  If the same object has different hashcode, the operation of the hash table will have unexpected results (expecting the Get method to return null), to avoid this problem, you need to keep in mind one: to replicate both the Equals method and the Hashcode method, rather than write only one of them.

the Hashtable is synchronous .

HashMap class

HashMap and Hashtable are similar, except that HashMap is non-synchronous and allows NULL, which is null value and null key. , but when HashMap is treated as collection (the values () method can return collection), its iteration sub-operation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the initialization capacity of the hashmap too high or load factor too low.

The difference between HashMap and Hashtable:

1, synchronization:Hashtable is synchronous , some methods in this class ensure that the object in the Hashtable is thread-safe. The HashMap is asynchronous , so objects in HashMap are not thread-safe. Because the requirements of synchronization affect the efficiency of execution, it is a good choice to use HashMap if you do not need a thread-safe collection, which avoids the unnecessary performance overhead associated with synchronization, thus improving efficiency.

2, Value: HashMap allows you to use NULL as the key or value of an entry for a table, but Hashtable cannot be placed in a null value. HashMap a maximum of one key value is null, but there can be countless multiple value values of NULL.

Attention:

1. The object used as key must implement the Hashcode and Equals methods.

2. The order of key-value pairs cannot be guaranteed

3, try not to use mutable objects as their key value.

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.

Weakhashmap and HashMap are basically the same, except that the latter's key retains a strong reference to the object, that is, as long as the HashMap object is not destroyed, the object referenced by all key objects is not garbage collected. HashMap also does not automatically delete the key-value pair objects for these keys. However, the objects referenced by the Weakhashmap key are not referenced by other strongly referenced variables, and the objects referenced by these keys may be recycled. Each key object in the Weakhashmap holds a weak reference to the actual object, and when the actual object corresponding to the key is reclaimed, Weakhashmap automatically deletes the key-value pair for that key.

 Public Static voidMain (string[] args) {weakhashmap W1=NewWeakhashmap (); //add three key-value pairs, three keys are anonymous strings, no other referencesW1.put ("language","Good"); W1.put ("Mathematics","Pass"); W1.put ("English","Medium"); W1.put ("Java","Good");//The key is a system-cached string ObjectSystem. out. println (W1);//Output {java=good, math = pass, English = medium, language = good}//notification system for garbage collectionSystem.GC ();    System.runfinalization (); System. out. println (W1);//output {Java=good}, no other referenced key-value pairs are recycled}

TREEMAP:

The map interface derives a sortmap subinterface, and the Sortmap implementation class is TreeMap. TreeMap is also based on the red-black tree to sort all keys, in two ways: natural sorting and custom sorting.

The TreeMap key is stored in the form of treeset, and the requirement for key is basically consistent with the requirements of the TreeSet element.

1, Map.entry firstentry (): Returns the key value pair corresponding to the minimum key, or null if Map is empty.

2, Object Firstkey (): Returns the minimum key, or null if it is empty.

3, Map.entry lastentry (): Returns the key value pair corresponding to the maximum key, or null if Map is empty.

4, Object Lastkey (): Returns the maximum key, or null if it is empty.

5. Map.entry higherentry (Object key): Returns a key-value pair that is located after key, or null if it is empty.

6. Map.entry lowerentry (Object key): Returns a key-value pair that is located before key, or null if it is empty.

7, Object Lowerkey (Object key): Returns a key value in front of key, or null if NULL.

8, Navigablemap subMap (Object fromkey,boolean fromlnclusive,object tokey,boolean toinciusive): Returns the map's child map, Its key range is from Fromkey to Tokey.

9, Sortmap SubMap (Object fromkey,object Tokey); Returns the map's child map, whose key range is from Fromkey (including) to Tokey (not included).

10, Sortmap Tailmap (Object Fromkey, Boolean inclusive): Returns the map's child map whose key range is greater than fromkey (whether it includes all keys depending on the second parameter).

11, Sortmap Headmap (Object Tokey, Boolean inclusive): Returns the map's child map whose key range is less than tokey (whether it includes all keys depending on the second parameter).

Summarize

  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.

Pay special attention to the operation of the hash table, and the object as key should correctly replicate the Equals and Hashcode methods.

Try to return the interface rather than the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client code does not have to be changed. This is for abstract programming.

A detailed description of data structures 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.