Collection Framework for "38" Java (container framework)

Source: Internet
Author: User
Tags iterable concurrentmodificationexception

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.
 

Collection vs Collections:

First, Collection and collections are two different concepts. The reason why they are put together is to make a better comparison. Collection is the root interface in the container hierarchy. And collections is a class that provides some static methods for handling container classes.

All the container implementation classes (such as ArrayList implementation of the list interface, HashSet implementation of the set interface) provide two ' standard ' constructors to implement: 1, an argument-free construction Method (void) 2, a single-parameter construction method with collection type, Used to create a new collection and its implementation class with the same elements as its parameters. In fact: Because all common container classes conform to the collection interface, the second method of construction is to allow the container to replicate with each other.

Class hierarchies for collection

Set Introduction

A collection that does not include duplicate elements, including mutable objects, is an unordered collection. The set does not contain elements that satisfy a.equals (b) to A and B, and there is a maximum of one null. The interfaces for implementing set are: Enumset, HashSet, TreeSet, etc.

Comparison of Hashset,treeset and Linkedhashset

A collection that does not include duplicate elements, including mutable objects, is an unordered collection. Set does not contain elements that are full a.equals (b) to A and B, and have a maximum of one null.
Mason's Memory Palace:
1, not allowed to contain the same elements

2, judging whether the object is the same, according to the Equals method

HashSet

A hash algorithm is used to store the elements in the collection, whose element values can be null. It does not guarantee the order in which elements are arranged. Similarly, HashSet is not synchronized, and if multiple threads are required to access it, you can use the Collections.synchronizedset method to wrap it:

Set s = Collections.synchronizedSet(new HashSet(...));

As in the previous section, when using iterators, you should also pay attention to concurrency modification exception concurrentmodificationexception.

The point to note is that the HashSet set determines that two elements are equal not only to the Equals method, but also to the Hashcode () method to return the values equally.

Linkedhashset

HashSet subclasses also have hashcode values to determine the position of the element. However, it maintains the order of elements using a list of links. Memorize two words: ordered.

Orderly refinement, reproduction. For example, a Mason implements a hashset unordered addition and then copies a hashset in the same order. The code is as follows:

Packagecom. Sedion. Bysocket. Collection;Import Java. Util. HashSet;Import Java. Util. Linkedhashset;Import Java. Util. Set;public class linkedhashlisttest{public static void Main (string[] args) {/ * Copy hashset * /        SetH1 = new hashset<string> ();H1. Add("List");H1. Add("Queue");H1. Add("Set");H1. Add("Map");System. out. println("HashSet Elements:");System. out. Print("\ T"+ H1 +"\ n");        SetH2 = Copy (H1);System. out. println("HashSet Elements after Copy:");System. out. Print("\ T"+ H2 +"\ n");} @SuppressWarnings ({"Rawtypes","Unchecked"}) public staticSetCopySet Set)    {SetSetcopy = new Linkedhashset (Set);Return setcopy;}}

Output:

HashSet Elements:    [MapQueueSetList]HashSet Elements After Copy:    [MapQueueSetList]
TreeSet

TreeSet is implemented using a tree structure (a red-black tree), and the elements in the collection are sorted, but the added, deleted, and included algorithm complexity is O (log (n)).

Summarize:

Hashset:equlas hashcode

Linkedhashset: Chain-structured

TreeSet: comparison, comparable interface, poor performance

List:

An ordered collection (also called a sequence) in which elements can be duplicated. Specifically, lists generally allow e1.equals (E2) elements to E1 and E2, and if the list itself allows null elements, they usually allow multiple null elements. The realization list has: ArrayList, LinkedList, Vector, stack and so on.

Comparison of ArrayList, LinkedList and vectors

Sequence (list), ordered collection, as it is named, is an ordered list of elements. Specifically, lists generally allow e1.equals (E2) elements to E1 and E2, and if the list itself allows null elements, they usually allow multiple null elements. The realization list has: ArrayList, LinkedList, Vector, stack and so on. It is worth mentioning that the vector is in the JDK1.1, and the list in the JDK1.2 when the time comes, we will talk about the difference between ArrayList and vector.

ArrayList vs. Vector

ArrayList is a sequence of resizable array implementations. As the element increases, its size increases dynamically. This class, in iterator or listiterator iterations, calls the Remove and add methods of the container itself to make modifications, throwing concurrentmodificationexception concurrency modification exceptions.

Note that this implementation is not synchronous. If more than one thread accesses a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, it must remain externally synchronized. (Structural modification refers to any action that adds or removes one or more elements, or explicitly adjusts the size of the underlying array; just setting the value of an element is not a structural modification.) This is typically done by synchronizing the objects that naturally encapsulate the list. If such an object does not exist, you should use the Collections.synchronizedlist method to "wrap" the list. This is best done at the time of creation to prevent accidental access to the list in a different step:

 List list = Collections.synchronizedList(new ArrayList(...));
Special attention:
@SuppressWarnings ({"Unchecked", "rawtypes"}) public static void Iteratortest () {List A1 = new arraylist<string> ();A1. Add("List01″");A1. Add("List02″");A1. Add("List04″");A1. Add("List05″");Iterator I1 = A1. Iterator();while (I1. Hasnext()) {Object obj = I1. Next();if (obj. Equals("List02″)") A1. Add("List03″");}system. out. Print("Collection: \n\t" +a1+ "\ n");}

Error running:
The problem description is clear that, after the iterator is created, the iterator throws Concurrentmodificationexception, unless the list is modified structurally by the Remove or add method of the iterator itself, or at any time in any way.

Switch
@SuppressWarnings ({"Unchecked","Rawtypes"}) public static void Listiterator () {List A1 = new arraylist<string> ();A1. Add("List01");A1. Add("List");A1. Add("List03");A1. Add("List04");Listiterator L1 = A1. Listiterator();while (L1. Hasnext()) {Object obj = L1. Next();if (obj. Equals("List")) {L1. Remove();L1. Add("List02");}} System. out. Print("collection: \n\t"+a1+"\ n");}

Vectors are very similar to ArrayList. As early as the JDK1.1, there was no known list interface, and now this class has been improved to implement the list interface. But unlike the new collection, vectors are synchronous. Vectors are much more expensive than ArrayList in the performance of queries.
There is almost no difference from the method, the same note: The function of this interface and the function of the Iterator interface are duplicated. Additionally, the Iterator interface adds an optional remove operation and uses a shorter method name. The new implementation should prioritize the use of the Iterator interface instead of the enumeration interface.

LinkedList and its performance ratio with ArrayList

LinkedList and ArrayList as the implementation of the list interface, LinkedList is the list interface linked list implementation. A list-based approach makes LinkedList better than ArrayList when inserting and deleting, while random access is less than ArrayList. The LinkedList implements all optional list operations and allows all elements to include NULL. In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue, or double-ended queue.

The method of LinkedList and ArrayList time complexity is summarized as shown.

LinkedList Introduction:

LinkedList relatively ArrayList add more methods, these methods are also good for the use of LinkedList implementation of the queue, two-way queue, stack, etc. provide good support.

LinkedList底层使用双向链表实现,一个节点持有前一个节点的引用、需要保存的元素的引用和后一节点的引用。空的LinkedList中first和last都为null,只有一个元素(节点)的LinkedList中first->next==last、last.prev==first。所有操作的底层就是对链表的操作,对链表实现了各种增删改查的方法,然后对外提供了更多操作行为,如队列的操作,栈的操作和普通List的操作,这些操作可能实际的实现是相同的,但是对外提供不同的接口以展示更多的行为。

LinkedList is a very powerful tool.

虽然LinkedList提供了很多操作,诸如栈和队列的,但有时候我们任然希望一个功能更专一的栈或队列,下面就演示以代理模式通过LinkedList实现的栈和队列:
Use of//linkedlist Public classTestuse { Public Static void Main(string[] args) {//Stackstack<integer> stack =NewStack<integer> (); for(intI=0;i<Ten; i++) Stack.push (i); System. out. println (Stack.peek ()); System. out. println (Stack.peek ()); System. out. println (Stack.pop ()); System. out. println (Stack.pop ()); System. out. println (Stack.pop ()); iterator<integer> Iterator = Stack.iterator (); while(Iterator.hasnext ()) System. out. Print (Iterator.next ()); System. out. println ();//Queuequeue<integer> queue =NewQueue<integer> (); for(intI=0;i<Ten; i++) Queue.enqueue (i); System. out. println (Queue.peek ()); System. out. println (Queue.peek ()); System. out. println (Queue.dequeue ()); System. out. println (Queue.dequeue ()); System. out. println (Queue.dequeue ()); iterator = Queue.iterator (); while(Iterator.hasnext ()) System. out. Print (Iterator.next ()); }}//Use the proxy mode to implement a stack using the LinkedListClass Stack<t> implements iterable<t>{Privatelinkedlist<t> stack =NewLinkedlist<t> (); PublicTPop(){//out of stack, will delete the top element of the stack        returnStack.poll (); } PublicTPeek(){//out stack, but does not remove top element of stack        returnStack.peek (); } Public void Push(T T) {//into the stackStack.push (t); } @Override PublicIterator<t>iterator() {returnStack.iterator (); }}//Use the proxy mode to implement a queue using LinkedListClass Queue<t> implements iterable<t>{Privatelinkedlist<t> queue =NewLinkedlist<t> (); Public void Enqueue(T T)    {Queue.offer (t); } PublicTdequeue(){returnQueue.poll (); } PublicTPeek(){returnQueue.peek (); } @Override PublicIterator<t>iterator() {returnQueue.iterator (); }}
A summary of the list:

First LinkedList is a doubly linked list, ArrayList and Vertor are arrays
Vector and ArrayList

1, vector is thread synchronization, so it is also thread-safe, and ArrayList is thread-asynchronous, is not secure.

2, remember the concurrency modification exception java.util.ConcurrentModificationException, priority to consider ArrayList, unless you are using multithreading required.

Aarraylist and LinkedList
1, for random access get and set,arraylist feel better than linkedlist,linkedlist to move the pointer.
2, in the new and delete operations Add and remove,linedlist more dominant, ArrayList to move the data.
3.
Single data insertion or deletion, ArrayList speed is better than linkedlist. The reason is: LinkedList data structure is three objects, the group size is more appropriate than the linked list, the direct assignment is over, no longer set the value of the pointer before and after.
If bulk random Insert delete data, LinkedList speed is much better than ArrayList. Because ArrayList each insertion of data, you move the insertion point and all subsequent data.

Queue:

A queue is a double-ended queue that supports inserting and removing elements at both ends of the head and tail, mainly including: Arraydeque, Linkedblockingdeque, LinkedList. The other is the blocking queue, which will throw an exception when the queue is full and then insert the element, including Arrayblockqueue, Priorityblockingqueue, Linkedblockingqueue. Although the interface does not define a blocking method, the implementation class extends this interface.

MAP:


MAP:

is a collection of key-value pairs. In other words, a map cannot contain duplicate keys, with each key mapped to a value. This interface replaces the dictionary abstract class. The implementation map has: HashMap, TreeMap, HashTable, Properties, Enummap.

HashMap and TreeMap

A map, also known as a mapping table, is an object that maps keys to values. There are four map sets that implement the map interface and are used frequently: hashmap,treemap,hashtable and Linkedhashmap.

1、一个映射不包含重复的键。2、每个键最多只能映射到一个值。
HashMap

HashMap is the implementation of a hash table-based map interface. It hashes the key, and the hash function can only be used for the key.
The Haspmap key must be unique, and the same key cannot hold two values, and if the Put method is called two times for the same key, the second value supersedes the first one. It is also permissible to use null values and NULL keys.
The following three points are important for HashMap:

1. HashMap constructor

The Haspmap constructor involves two parameters: the initial capacity and the load factor. The initial initial capacity is the content of the bucket in which the hash table is created. A load factor is a scale in which a hash table can reach a full amount before its capacity increases automatically. Both of these parameters affect the performance of the HashMap. The default constructs one with the default initial capacity (16) and the default load factor (0.75). The default load factor (. 75) is a tradeoff in time and space costs.

2, and the last summary of the set are similar, this hashmap thread is not safe and out of sync. If you want to prevent accidental occurrences, you can set up synchronization:

Map m = Collections.synchronizedMap(new HashMap(...));

3, different steps, means that there is a rapid failure caused by the concurrency modification exception.

TreeMap

Reemap is implemented using a tree structure (a red-black tree), and the elements in the collection are sorted, but the added, deleted, and included algorithm complexity is O (log (n)).

1, TreeMap implements the SortedMap, as the name implies, it is represented as having a sorted collection.

2, the same key can not hold two values, if the same key two calls the Put method, the second value will replace the first value.

Summarize:
1.  HashMap通过hashcode对其内容进行快速查找,而TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不固定的)。集合框架”提供两种常规的Map实现:HashMap和TreeMap (TreeMap实现SortedMap接口)。2.  2.在Map 中插入、删除和定位元素,HashMap 是最好的选择。但如果您要按自然顺序或自定义顺序遍历键,那么TreeMap会更好。使用HashMap要求添加的键类明确定义了hashCode()和 equals()的实现。 这个TreeMap没有调优选项,因为该树总处于平衡状态。
Interface Summary:

Summary: Vectors and ArrayList

1,vector is thread-synchronized, so it is thread-safe, and ArrayList is thread-asynchronous and unsafe. If the thread security factors are not taken into account, the ArrayList efficiency is generally higher.
2, if the number of elements in the collection is greater than the length of the current collection array, the vector growth rate is 100% of the current array length, while the ArrayList growth rate is 50% of the current array length. If you use data with larger data volumes in a collection, vector has some advantages.
3, if you look for a specified location of data, the vector and ArrayList use the same time, are 0 (1), this time using both vector and ArrayList can be. If moving a data at a specified location takes 0 (n-i) n for the total length, this should take into account the use of linklist, since it takes 0 (1) to move the data at a specified location, and the time to query the data at a specified location is 0 (i).

ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, allowing direct ordinal index elements, but inserting data to design memory operations such as array element movement, so the index data is fast inserting data slowly, Vector because of the use of the Synchronized method (thread safety) so the performance is worse than the ArrayList, LinkedList using the two-way linked list to implement storage, indexed by ordinal data needs to be traversed forward or backward, but when inserting data only need to record the item's front and rear items, So insert several faster!

Aarraylist and LinkedList

1.ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist feel better than LinkedList, because linkedlist to move the pointer.
3. Add and Remove,linedlist are the dominant for new and deleted operations because ArrayList is moving the data.
This point depends on the actual situation. If you insert or delete only a single piece of data, the ArrayList speed is better than LinkedList. But if bulk random insert deletes data, LinkedList speed is much better than ArrayList. Because ArrayList each insertion of data, you move the insertion point and all subsequent data.

HashMap and TreeMap

1, HashMap through the hashcode of its content to quickly find, and treemap all the elements are kept in a fixed order, if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed). The order of the elements in the HashMap is not fixed.

2, HashMap through the hashcode of its content to quickly find, and treemap all the elements are kept in a fixed order, if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed). The collection framework provides two general map implementations: HashMap and TreeMap (TreeMap implements the SortedMap interface).

3, inserting, deleting and locating elements in map, HashMap is the best choice. But if you want to traverse the key in natural order or in a custom order, TreeMap is better. The implementation of Hashcode () and Equals () is clearly defined by the key class that is required to be added using HashMap. There is no tuning option for this treemap because the tree is always in a balanced state.

Hashtable and HashMap

1, historical reason: Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2.

2, synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is a line program is not secure, not synchronous.

3. Value: Only HashMap can let you use NULL as the key or value of an entry for a table.
Reference blog:
The main reference to Mason's blog is the following two other blogs, which are linked as follows:
http://www.bysocket.com/?p=424
http://anxpp.com/index.php/archives/656/
http://blog.csdn.net/softwave/article/details/4166598

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:


http://my.csdn.net/u010321471

Collection Framework for "38" Java (container framework)

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.