Java Collection Framework List-map-set

Source: Internet
Author: User
Tags set set

Basic interface/class hierarchy for 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
Collection interface
Collection is the most basic set interface, and a collection represents a set of objects that are called collection elements. All classes that implement the collection interface must provide two standard constructors: the parameterless constructor is used to create an empty collection, and a constructor with a collection parameter is used to create a new collection, which A 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:
Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
Depending on the purpose, collection is divided into lists and sets.
The list interface list inherits from the collection 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 set sets, the list allows repeating elements. For E1 and E2 object elements that meet the E1.equals (E2) condition, they can exist in the list collection at the same time. Of course, there is also a list implementation class that does not allow the existence of duplicate 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.
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 LinkedList (...));
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).
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, Some elements have been added or removed, Concurrentmodificationexception will be thrown when the iterator method is called, 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
The set inherits from the collection interface. Set is a collection that cannot contain duplicate elements, that is, the E1 and E2 object elements that satisfy the e1.equals (E2) condition cannot exist in the same set set at the same time, in other words, any two elements in the set set E1 and E2 satisfy E1.equals (e2) = = False condition, set has at most one null element.
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.
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.
HashSet class
This class implements the Set interface, which is supported by a hash table (actually a HashMap instance). It does not guarantee the iteration order of the collection, especially because it does not guarantee that the order is constant. This class allows the use of NULL elements.
HashSet is not synchronous, you need to use the following statement for the S synchronous transformation:
Set s = collections.synchronizedset (new HashSet (...));
Map interface
Map does not inherit the collection interface. In other words, map and collection are 2 different sets. Collection can be thought of as a collection of (value), and map can be thought of as a collection of (Key,value).
The map interface provides 3 types of collection views, a set of key collections, a set of value collections, or a set of key-value mapping relationships, from the contents of the map.
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":
Hashtable numbers = new Hashtable ();
Numbers.put ("One", New Integer (1));
Numbers.put ("n", New Integer (2));
Numbers.put ("Three", New Integer (3));
To take out a number, say 2, with the corresponding key:
Integer n = (integer) numbers.get ("a");
System.out.println ("both =" + N);
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.
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.
Tool classes for collection operations
Java provides java.util.Collections, and the Java.util.Arrays class simplifies operations on collections
Java.util.Collections mainly provides some static methods for manipulating or creating collections such as Collection,map.
Java.util.Arrays mainly provides static methods for manipulating arrays.
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.
Use Hashset,hashmap in addition to treeset,treemap when sorting is required, because they are more efficient.
Pay special attention to the operation of the hash table, and the object as key should 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 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.

Attention:
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, generally use 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 element 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.
=============================================
Just take it! Super-practical Java Array tips
Summary: This article shares the top 11 methods of Java arrays to help you solve your workflow problems, either in a team environment or in a private project, and you can use them directly.
0. Declare an array (Declare an array)
string[] Aarray = new STRING[5];
String[] Barray = {"A", "B", "C", "D", "E"};
string[] CArray = new string[]{"A", "B", "C", "D", "E"};
1. Output an array from Java (print an array in Java)
Int[] Intarray = {1, 2, 3, 4, 5};
String intarraystring = arrays.tostring (Intarray);
Print directly would print reference value
System.out.println (Intarray);
[[Email protected]
System.out.println (intarraystring);
[1, 2, 3, 4, 5]
2. Create an array list from the array (create a ArrayList from an array)
String[] Stringarray = {"A", "B", "C", "D", "E"};
arraylist<string> ArrayList = new Arraylist<string> (arrays.aslist (Stringarray));
System.out.println (arrayList);
[A, B, C, D, E]
3. Check if the array contains a specific value (check if an array contains a certain value)
String[] Stringarray = {"A", "B", "C", "D", "E"};
Boolean B = Arrays.aslist (Stringarray). Contains ("a");
System.out.println (b);
True
4. Connect two arrays (concatenate two arrays)
Int[] Intarray = {1, 2, 3, 4, 5};
Int[] IntArray2 = {6, 7, 8, 9, 10};
Apache Commons Lang Library
int[] Combinedintarray = Arrayutils.addall (Intarray, intArray2);
5. Declare an array of inline chains (Declare an array inline)
Method (New string[]{"A", "B", "C", "D", "E"});
6. Add an array element to a separate string (Joins the elements of the provided array into a single string)
Containing the provided list of elements
Apache Common Lang
String j = stringutils.join (new string[] {"A", "B", "C"}, ",");
System.out.println (j);
A, B, c
7. Converting an array list into an array (Covnert a ArrayList to an array)
String[] Stringarray = {"A", "B", "C", "D", "E"};
arraylist<string> ArrayList = new Arraylist<string> (arrays.aslist (Stringarray));
string[] Stringarr = new string[arraylist.size ()];
Arraylist.toarray (Stringarr);
for (String S:stringarr)
System.out.println (s);
8. Convert an array into a collection (convert an array to a set)
set<string> set = new Hashset<string> (arrays.aslist (Stringarray));
SYSTEM.OUT.PRINTLN (set);
[D, E, B, C, a]
9. Inverse Array (Reverse an array)
Int[] Intarray = {1, 2, 3, 4, 5};
Arrayutils.reverse (Intarray);
System.out.println (arrays.tostring (Intarray));
[5, 4, 3, 2, 1]
10. Delete the array element (remove element of an array)
Int[] Intarray = {1, 2, 3, 4, 5};
int[] removed = Arrayutils.removeelement (Intarray, 3);//create a new array
System.out.println (arrays.tostring (removed));
One more–convert int to byte array

byte[] bytes = bytebuffer.allocate (4). Putint (8). Array ();
for (byte t:bytes) {
System.out.format ("0x%x", t);

}

http://wangzhaoli.blog.51cto.com/7607113/1257601

http://blog.csdn.net/dlf123321/article/details/40824877

Java Collection Framework List-map-set

Related Article

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.