Java Container Class---overview

Source: Internet
Author: User
Tags comparable concurrentmodificationexception

1. Container class Diagram



The dashed box represents the interface.


A solid Line box represents an entity class.


A thick wireframe represents the most frequently used entity class.
The arrow of the dot line indicates that the interface is implemented.
A solid arrow indicates that the class can manufacture an object of the class that the arrow refers to.

The Java Collection Toolkit is located under the Java.util package. It includes many data structures that are used frequently, such as arrays, lists, stacks, queues, collections, hash tables , and so on. The Learning Java Collection Framework can be broadly divided into the following five parts: list lists, set sets, map mappings, iterators (Iterator, enumeration), tool classes (Arrays, collections).

It can be seen that the collection class is divided into two major categories: collection and map.


Collection is a list, set and other sets of highly abstracted interface, it includes the basic operation of these sets, it is mainly divided into two parts: list and set.


The list interface usually represents a single listing (array, queue, linked list, stack, etc.), in which the elements can be repeated. The implementation classes are often used as ArrayList and LinkedList, and there are vectors that are not used frequently. Other than that. LinkedList also implements the queue interface, so it can also be used as a queue.



The set interface usually represents a collection in which the elements differ in meaning (guaranteed by hashcode and the Equals function), often using implementation classes with HashSet and TreeSet. The hashset is implemented through the HashMap in the map, and TreeSet is achieved through the TREEMAP in the map. In addition, TreeSet implements the SortedSet interface, so it is an ordered set (the elements in the collection implement the comparable interface and overwrite the Compartor function).



We see. Abstract classes Abstractcollection, Abstractlist, and Abstractset respectively implement the collection, list, and set interfaces, which is the very many adapter design patterns used in the Java collection framework, Use these abstract classes to implement interfaces, implement some or all of the methods in an abstract class, so that some of the following classes simply inherit the abstract class directly and implement the method they need without implementing all the abstract methods in the interface.



Map is a mapping interface in which each element is a Key-value key-value pair. The same abstract class Abstractmap implements most of the functions in the map interface through the adapter pattern, TreeMap, HashMap, Weakhashmap and other implementation classes are implemented by inheriting Abstractmap. In addition, the infrequently used Hashtable directly implements the map interface. Both it and Vector are the collection classes introduced by JDK1.0.

Iterator is an iterator that iterates through a collection (it cannot traverse the map, just to traverse collection). The collection implementation class implements the iterator () function. It returns a Iterator object. Used to iterate through the collection, Listiterator is used specifically to traverse the list. And enumeration is JDK1.0 when introduced, the function and iterator same. But it has less function than iterator. It can only be used again in Hashtable, vectors, and stacks.

Arrays and collections are the two tool classes used to manipulate arrays and collections. For example, the arrays.copyof () method is called extensively in ArrayList and vectors. There are many static methods in collections that return the synchronized version number of each collection class, which is the thread-safe version number. Of course. Suppose you want to use a thread-safe binding class, prefer the corresponding collection class under the concurrent concurrent package.


2. The container class holds the object way

1 Collection: just agree to put an object in each position . It contains a list of "holding a set of objects in a certain order". And "Just be able to agree to join the non-recurring object" set.

You can add elements to the collection object using the Add () method.

2 Map: A set of "key-value" (Key-value) in the form of Pair,map also do not accept the repeated key value.

You can use the put () method to add elements to a map.


The difference between Collection and collections:
Collections is a Java.util class that includes a variety of static methods for collection operations, such as searching, sorting, and threading security for various collections.
The collection is an interface under a java.util . It is the parent interface for various collection structures. the interfaces that inherit from it are mainly set and list.


3.Iterator Interface

Discover a feature, all of the above collection classes. the iterator interface is implemented ,

This is an interface for iterating through the elements in the collection, mainly including Hashnext (), Next (), and remove () three methods. One of its sub-interfaces Listiterator adds three methods on top of it, each of which is add (), previous (), hasprevious (). That is to say that the implementation of the iterator interface, then in the collection of elements in the time, only the backward traversal, the traversed element will not be traversed, usually the unordered collection is implemented by this interface. For example HashSet. HashMap;

And those elements of an ordered collection, the implementation of the general is the Listiterator interface , the implementation of this interface can be a set of two-way traversal, both through the next () access to the next element, but also through the previous () access to the previous element, For example ArrayList.

Abstract class:
Another feature is the use of abstract classes.

Suppose you want to implement a collection class yourself. To implement those abstract interfaces can be cumbersome and a lot of work.

Abstract classes can be used at this time, and these abstract classes provide us with a lot of out-of-the-box implementations. We just need to rewrite some methods based on our own needs or add some methods to achieve the collection class we need. The work flow is greatly reduced.


4. Set interface

Set is a collection that does not include repeated elements, that is, the random two elements E1 and E2 have E1.equals (E2) =false, andset has a maximum of one null element .
It is very obvious that the constructor of the set has a constraint that the incoming collection argument cannot include repeated elements.
Note: Variable objects (Mutable object) must be handled with care. Assuming that a mutable element in a set alters its own state causes object.equals (Object) =true to cause some problems.


Set inference two objects are also not using the = = operator, but are based on the Equals method. Other words. Only two objects returned True,set with the Equals method would not accept the two objects.

4.1 HashSet

HashSet: is a subclass of the set interface. The basic feature is that it cannot store repeated elements, and uses a hash of the storage method, so there is no order .

There is no order here: the order in which the elements are inserted is inconsistent with the order of the outputs.


HashSet has the following features:
The order of elements cannot be guaranteed and the order may change
It's not synchronous.
The collection element can be null, but it can only be placed in a null


When an element is deposited into the HashSet Union. HashSet calls the object's Hashcode () method to get the Hashcode value of the object, and then determines where the object is stored in HashSet, based on the hashcode value.


Simply put, the hashset set infers that two elements are equal by two objects that are more equal by the Equals method. and the Hashcode () method of two objects returns a value equal
Note that if you want to put an object in HashSet, override the Equals method of the corresponding class for that object, and you should override its Hashcode () method.

The rule is that if two objects return true through the Equals method, their hashcode should also be the same. In addition, the attribute used in the object as the equals criterion should be used to calculate the value of the hashcode.




4.2 Linkedhashset
The Linkedhashset collection is the same as the element's hashcode value to determine where the element is stored . But it maintains the order of elements using the list at the same time. This makes the elements appear to be saved in an insertion order, that is, when the collection is traversed, Linkedhashset will access the elements of the collection in the order in which they are added.

Linkedhashset when iterating through all the elements in set. Performance is better than HashSet, but performance is slightly inferior to hashset when plugged in.


4.3 TreeSet class
TreeSet is the only implementation class for the SortedSet interface. TreeSet ensures that the collection element is in the sorted state .

TreeSet supports two sorting methods, natural sorting and custom sorting, in which the natural sort is the default sorting method.

The object that is added to the treeset should be the same class.
TreeSet infers that two objects are unequal by two objects that return false through the Equals method, or that the CompareTo method does not return 0


Natural sort:
Natural sorting uses the CompareTo (Object obj) method to sort the elements to compare the size of the elements, and then arranges the elements in ascending order.
Java provides a comparable interface that defines a CompareTo (object obj) method that returns an integer value that implements the object of the interface to be comparable in size.
The Obj1.compareto (Obj2) method assumes that 0 is returned, indicating that two objects are equal, assuming a positive number is returned. Indicates that the OBJ1 is greater than obj2 and assumes a negative number, indicating that the obj1 is less than obj2.
Assuming that we always return true for the Equals method of two objects, the CompareTo method returned by the two objects should return 0


Custom sorting
The natural sort is based on the size of the collection element. in ascending order. Suppose you want to customize the ordering, you should use the comparator interface to implement the int compare (T o1,t O2) method


5. List interface

The list is an orderly collection. Use this interface to precisely control where each element is inserted. The user can use the index (where the element is in the list, similar to an array subscript) to access the elements in the list. This is similar to an array of java. The list agrees to have 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 a number of add () and other methods, agree to join. Delete, set element. can also traverse forward or backward.


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



5.1 LinkedList Class
The LinkedList implements the list interface. agrees with the null element .

In addition, LinkedList offers additional get,remove. The Insert method is at the header or 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 . Assuming that multiple threads access a list at the same time, you must implement your own access synchronization.

One workaround is to construct a synchronized list when the list is created:
List List = Collections.synchronizedlist (new LinkedList (...));


5.2 ArrayList Class
ArrayList implements a variable-size array. It agrees with all elements. Contains null.

ArrayList is not synchronized.
Size,isempty,get,set method Execution time is constant. However, the Add method cost is the shared constant. Adding n elements requires an O (n) time.

The other method execution time is linear.
Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements.

This capacity can be added to your own initiative as you add new elements . 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 add ArrayList capacity to improve insertion efficiency.


Like LinkedList, ArrayList is also unsynchronized (unsynchronized).



5.3 Vector Class
Vectors are very similar to ArrayList, but vectors are synchronous .

The iterator created by the vector, although the iterator created by the ArrayList are the same interface. However, because vectors are synchronous. When a iterator is created and is being used, there is a thread that changes the state of the vector (for example, by adding or removing some elements), and when the iterator method is called, the concurrentmodificationexception is thrown. Therefore, the exception must be caught.



5.4 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 main push and pop methods. And the Peek method gets the stack top element, the empty method tests whether the stack is empty, and the search method detects the position of an element in the stack. Stack has just been created as an empty stack.



The difference between ArrayList and vectors:
I. Synchronicity:
vectors are thread-safe. In other words, it is synchronous. And ArrayList is the thread program is unsafe, not synchronous. The iterator created by the vector, although the iterator created by the ArrayList are the same interface. However, since vectors are synchronous, when a iterator is created and being used, there is a thread that changes the state of the vector (for example, adding or removing elements). When the iterator method is called, Concurrentmodificationexception is thrown, so the exception must be caught.


two. Data growth: when growth is required, vectors grow by default to the original, while ArrayList is half the original


Array and Arrays:
An array is a Valarray
. A fixed length container. Once you create this object, you cannot change its size (capacity).
Arrays is the tool class for array , and its static method defines the various operations on the array:


5. Map interface
Note thatmap does not inherit the collection interface , and map provides a key-to-value mapping. the same key cannot be included in a map. Each key can only map a value. The map interface provides views of 3 collections. The contents of a map can be treated as a set of key sets, a set of value sets, or a set of key-value mappings.


5.1 Hashtable class
Hashtable inherits the map interface to implement a key-value mapped hash table. Any object that is non-empty (non-null) can be either a key or a value. the Hashtable is synchronous.
Adding data using put (key, value), taking out the data using get (key), the time overhead for these two basic operations is constant.


Using Hashtable's simple scale, such as the following, put the three-to-one into Hashtable, their key each is "a", "two", "three":

Hashtable numbers = new Hashtable ();    Numbers.put ("One", New Integer (1));    Numbers.put ("n", New Integer (2)); Numbers.put ("Three", New Integer (3));</span>

to take out a number, for example 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, assuming you use your own defined class as the key. Be quite careful, according to the definition of the hash function, assuming that two objects are the same, namely Obj1.equals (OBJ2) =true, their hashcode must be the same. But suppose two objects are different. Their hashcode is not necessarily different, assuming that two different objects of the hashcode same, such a phenomenon is called conflict, the conflict will cause the operation of the hash table time overhead increases, so as far as possible to define a good hashcode () method, can speed up the operation of the hash table.


Assuming that 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, just need to remember one: the same time to replicate the Equals method and Hashcode method, and not just write one.

5, 2 HashMap class
HashMap and Hashtable are similar, except that HashMap is not synchronous . and agree to null. That is, null value and null key. However, when HashMap is treated as collection (the values () method returns collection), its iterative sub-operation time overhead is proportional to the capacity of HashMap. Therefore, assuming that the performance of an iterative operation is quite important, do not set the initialization capacity of the hashmap too high. Or the load factor is too low.




5.3 Weakhashmap Class
Weakhashmap is an improved hashmap. It implements a "weak reference" to key, assuming that a key is no longer referenced externally, then the key can be recycled by GC.


The difference between HashMap and Hashtable:
The application of Hashtable is very extensive. HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation). HashMap is the class used in the new framework to replace Hashtable. This means that HashMap is recommended. Do not use Hashtable.
The 1.HashTable method is synchronous. HashMap is not synchronized, so in multi-threaded situations to manually synchronize HashMap this difference is like vector and ArrayList.


2.HashTable does not agree with null values (neither key nor value can), HashMap agrees to null values (both key and value are capable).


3.HashMap removed the contains method of Hashtable. Changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding.
4.HashTable use Enumeration,hashmap with iterator.


Summarize
Assumptions involve operations such as stacks, queues, and so on. Should consider using list, for the need for high-speed insertion, delete elements, should use LinkedList, assuming the need for high-speed random access elements. You should use ArrayList.
It is more efficient to assume that the program is in a single-threaded environment, or that access is only done in one thread, considering the non-synchronous classes. Suppose that multiple threads might manipulate a class at the same time, you should use a synchronized class.




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. If you return to list instead of ArrayList, assume that you need to change ArrayList to LinkedList later. The client code does not have to change.

This is for abstract programming.



Source of references:

The difference between Hashset,treeset and Linkedhashset

Java Container class parsing

Java Collection source code anatomy Java Collection Framework



Java Container Class---overview

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.