On the implementation of common data structure in Java class collection and Map_java

Source: Internet
Author: User
Tags comparable static class

Linear table, linked list, hash table is a commonly used data structure, in the Java development, JDK has provided us with a series of corresponding classes to achieve the basic data structure. These classes are in the Java.util package. This paper attempts to explain the roles of the classes and how to use them correctly by a simple description.

Collection 
├list 
│├linkedlist 
│├arraylist 
│└vector │└stack └set 
Map 
├hashtable 
├hashmap 

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 be sorted and others not. The Java SDK does not provide classes that directly inherit 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: parameterless constructors are used to create an empty collection, and a constructor for a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection. The latter constructor allows the user to replicate 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 can be used to access each element of the collection one at a time.

Typical usage is as follows:

Iterator it = Collection.iterator (); Gets an iterative child while 
(It.hasnext ()) { 
Object obj = It.next ();//Get the next element 
} 

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

List Interface

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

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

In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards.

Common classes that implement the list interface are Linkedlist,arraylist,vector and stack.

LinkedList class

LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).

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

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

ArrayList class

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

The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The 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 can automatically increase 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 increase the insertion efficiency.

Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

Vector class

Vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, although the same interface was created with ArrayList, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, Add or remove some elements), the concurrentmodificationexception is thrown when the iterator method is invoked, so the exception must be caught.

Stack class

Stack inherits from the vector, implementing a LIFO stack. Stack provides 5 additional methods that allow vectors to be used as stacks. Basic push and Pop methods, and Peek method to get the top of the stack elements, empty method test stack is empty, the search method detects an element in the stack position. Stack is just created after stack is empty.

set Interface

A 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 the set has a constraint, and the incoming collection parameter cannot contain duplicate elements.

Note: You must be careful to manipulate variable objects (mutable object). If a variable element in a set changes its state, causing the Object.Equals (Object) =true to cause some problems.

Map Interface

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

Hashtable class

Hashtable implements the map interface to implement a key-value mapping hash table. Any object that is Non-null (non-null) can be a key or value.

Adding data using put (key, value), fetching data using get (key), the time cost of these two basic operations is constant.

Hashtable adjusts performance by initial capacity and load factor two parameters. Typically, the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put.

Using Hashtable for example, put 1,2,3 into Hashtable, their key is "one", "two", "three":

Hashtable numbers = new Hashtable ();
Numbers.put ("One", New Integer (1));
Numbers.put ("Two", New Integer (2));
Numbers.put ("Three", New Integer (3));

To remove a number, such as 2, use the corresponding key:

Integer n = (integer) numbers.get ("two");
System.out.println ("two =" + N);

Because an object that is a key will determine the location 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 a key, be very careful, as defined by the hash function, if two objects are the same, that is, Obj1.equals (OBJ2) =true, Their hashcode must be the same, but if two objects are different, their hashcode is not necessarily different, and if the hashcode of two different objects is the same, this phenomenon is called conflict, and the conflict causes the time overhead of manipulating the hash table, so as to define the hashcode () method to speed up the operation of the hash table.

If the same object has a different hashcode, the operation of the hash table will have unexpected results (the expected GET method returns null), to avoid this problem, you need to keep in mind one: you have to copy both the Equals method and the Hashcode method, not just one.

The Hashtable is synchronized.

HashMap class

HashMap is similar to Hashtable, except that HashMap is unsynchronized and allows NULL, that is, null value and null key. , but when HashMap is treated as collection (the values () method returns collection), its iterative child operation time cost is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is significant, do not set the HASHMAP initialization capacity too high, or the load factor too low.

Weakhashmap class

Weakhashmap is an improved hashmap, which implements a "weak reference" to key, and if a key is no longer referenced externally, the key can be reclaimed by GC.

Summary

If you are involved in stacks, queues, and other operations, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.

Java.util.Collections Class Package

The Java.util.Collections class contains many useful ways to make it easier for programmers to work, but these methods are often not fully exploited. Javadoc gives the most complete description of the Collections class: "This class contains a private static class that can manipulate or return a collection."
"1.2 Contains methods
Iterator, ArrayList, Elements, Buffer, map,collections

Liezi:

Import java.util.ArrayList; 
Import java.util.Collection; 
Import java.util.Collections; 
Import Java.util.Comparator; 
Import java.util.List; 

public class Collectionssort {public 
collectionssort () { 

} public 

static void Main (string[] args) { 
Double array[] = {A, n, 456, 231}; 
List List = new ArrayList (); 
List li = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
List.add ("" "+array[i]); 
} 
Double arr[] = {}; 
for (int j=0;j<arr.length;j++) { 
li.add (new Double (ARR[J)); 
} 

2. Specific operation

1) Sorting (sort)

Use the Sort method to sort the specified list in ascending order based on the nature of the elements. All elements in the list must implement the comparable interface. All elements in this list must be comparable to each other by using the specified comparer

Double array[] = {112, n, 456, 231}; 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections.sort (list); 
for (int i = 0; i < Array.Length i++) { 
 System.out.println (Li.get (i)); 
} 
Result: 112,111,23,456,231 

2) mixed row (shuffling)

The blending algorithm does exactly the opposite of sort: it disrupts any sort of trail that might be in a list. That is, an input that is based on a random source rearranges the List so that the arrangement has the same probability (assuming that the random source is fair). This algorithm is very useful in implementing a game of chance. For example, it can be used to mix a List of card objects that represent a deck of cards. In addition, it is also useful when generating test cases.

Collections.shuffling (list) 
double array[] = {112, n, 456, 231}; 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections.shuffle (list); 
for (int i = 0; i < Array.Length i++) { 
 System.out.println (Li.get (i)); 
} 
Result: 112,111,23,456,231 

3) reversal (Reverse)

You can use the reverse method to sort the specified list in descending order based on the nature of the elements.

Collections.reverse (list) 
double array[] = {112, n, 456, 231}; 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections. Reverse (list); 
for (int i = 0; i < Array.Length i++) { 
 System.out.println (Li.get (i)); 
} 
Result: 231,456,23,111,112 
4 replaces 
all elements in the specified list with the specified element (Fill). 
String str[] = {"dd", "AA", "BB", "CC", "ee"}; 
for (int j=0;j<str.length;j++) { 
li.add (new String (STR[J)); 
} 
Collections.fill (Li, "AAA"); 
for (int i = 0; i < li.size (); i++) { 
System.out.println ("list[" + i + "]=" + li.get (i)); 

} 
Result: AAA,AAA,AAA,AAA,AAA 

5) Copy (copy)

With two parameters, a target list and a source list, the elements of the source are copied to the target, overwriting its contents. The target List is at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.

Collections.copy (List,li): The next argument is the target list, the previous one is the source list

Double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
List li = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Double arr[] = {1131,333}; 
String str[] = {"dd", "AA", "BB", "CC", "ee"}; 
for (int j=0;j<arr.length;j++) { 
li.add (new Double (ARR[J)); 
} 
Collections.copy (List,li); 
for (int i = 0; I <list.size (); i++) { 
System.out.println ("list[" + i + "]=" + list.get (i)); 
} 

6) returns the smallest element in the collections (min)

Returns the smallest element of a given collection, based on the order in which the comparer is produced. All elements in the collection must be comparable by specifying the comparer

Collections.min (list) 
double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections.min (list); 
for (int i = 0; I <list.size (); i++) { 
System.out.println ("list[" + i + "]=" + list.get (i)); 
} 
Results: 23 

7) returns the smallest element in collections (max)

Returns the maximum element for a given collection, based on the order in which the comparer is produced. All elements in the collection must be comparable by specifying the comparer

Collections.max (list) 
double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections.max (list); 
for (int i = 0; I <list.size (); i++) { 
System.out.println ("list[" + i + "]=" + list.get (i)); 
} 
Results: 456 

8) Lastindexofsublist

Returns the starting position of the specified destination list for the last occurrence of the specified source list

int count = Collections.lastindexofsublist (List,li); 
Double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
List li = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Double arr[] = {}; 
String str[] = {"dd", "AA", "BB", "CC", "ee"}; 
for (int j=0;j<arr.length;j++) { 
li.add (new Double (ARR[J)); 
} 
INT locations = Collections. Lastindexofsublist (List,li); 
System.out.println ("= = =" + locations); 
Result 3 

9) Indexofsublist

Returns the starting position of the specified destination list for the first occurrence in the specified source list

int count = Collections.indexofsublist (List,li); 
Double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
List li = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Double arr[] = {}; 
String str[] = {"dd", "AA", "BB", "CC", "ee"}; 
for (int j=0;j<arr.length;j++) { 
li.add (new Double (ARR[J)); 
} 
INT locations = Collections.indexofsublist (List,li); 
System.out.println ("= = =" + locations); 
Result 1 

Rotate)

Loops the elements in the specified list, based on the specified distance
Collections.rotate (list,-1);
If it is a negative number, the positive move, and a positive number moves in the direction

Double array[] = {112, n, 456, 231}; 
List List = new ArrayList (); 
for (int i = 0; i < Array.Length i++) { 
list.add (new Double (Array[i)); 
Collections.rotate (list,-1); 
for (int i = 0; I <list.size (); i++) { 
System.out.println ("list[" + i + "]=" + list.get (i)); 
} 

The above article discusses the Java commonly used data structure realization class collection and the map is small arranges to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

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.