The main implementation class of collection interface and map interface in Java

Source: Internet
Author: User
Tags array length comparable

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:
Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
The two interfaces derived from the collection interface are list and set only.

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

===============================================

List interface

The list interface is a simple extension of collection, and its concrete implementation classes are often ArrayList and LinkedList. You can put anything in a list container and take it out when you need it. ArrayList can be seen in its name as an array-like form of storage, so its random access speed is very fast, and LinkedList's internal implementation is a linked list, it is suitable for in the middle of the list of links need to frequently insert and delete operations. The application can be freely selected as needed. The iterator can only walk forward through the container, while Listiterator inherits the iterator idea and provides a way to iterate through the list.

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.

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 iterator created by the ArrayList is the same interface, but because the vector is synchronous, when a iterator is created and is being used, Another thread changed the state of the vector (for example, adding or removing some elements), and when the method called iterator would throw concurrentmodificationexception, 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.

The difference between the implementation classes of the list interface

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 that performance than ArrayList ,LinkedList using a doubly linked list for storage , index data by ordinal need to be traversed forward or backward, But inserting the data only needs to record the item's front and rear items, so the insertion is faster!

Synchronization of

the vectors are synchronized. some of the methods in this class ensure that the objects in the vector are thread-safe. The ArrayList is asynchronous , so objects in ArrayList are not thread-safe. Because the requirements of synchronization affect the efficiency of execution, it is a good choice to use ArrayList if you do not need a thread-safe collection, which avoids unnecessary performance overhead due to synchronization.

Data growth

From an internal implementation mechanism, both ArrayList and vectors use arrays to control the objects in the collection. When you add elements to both types, if the number of elements exceeds the current length of the internal array, they all need to extend the length of the internal array, and vector automatically grows the array length by default, ArrayList is the original 50%. So in the end you get this collection that takes up more space than you actually need. So if you're going to save a lot of data in a collection then there are some advantages to using vectors, because you can avoid unnecessary resource overhead by setting the initialization size of the collection.

Usage patterns

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. In ArrayList and vectors, it takes the same amount of time to find the data from a specified location (through an index) or to add or remove an element at the end of the collection, as shown in O (1). However, if an element is added or removed elsewhere in the collection, the time spent will grow linearly: O (n-i), where n represents the number of elements in the collection, and I represents the index position at which the element is incremented or removed. Why is that? It is assumed that all elements after the first and second elements of the collection will perform the operation of the displacement. What does all this mean?
This means that you just look for elements in a particular location or only add and remove elements at the end of the collection, so you can use either a vector or a ArrayList. If this is another operation, you might want to choose a different collection operation class. For example, does the Linklist collection class take the same amount of time to add or remove elements from any location in the collection? O (1), but it is slow to use an element in the index-O (i), where I is the position of the index. It's also easy to use ArrayList because you can simply use an index instead of creating an iterator object. Linklist also creates objects for each inserted element, all of which you have to understand that it also brings additional overhead.
Finally, in the book Practical Java, Peter Haggar suggests using a simple array instead of a vector or ArrayList. This is especially true for programs with high efficiency requirements. Because the use of arrays (array) avoids synchronization, additional method calls, and unnecessary reallocation of space operations.

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.
===============================================

Set interface

The set interface is also an extension of collection, and unlike list, the object element in set cannot be duplicated , meaning you cannot put the same thing two times into the same set container. Its commonly used concrete implementation has HashSet and TreeSet class. HashSet can quickly locate an element, but the object you put into HashSet needs to implement the Hashcode () method, which uses the algorithm of the previously mentioned hash code . and TreeSet will put the elements in order to store, which requires you to put the object is sortable , which is used in the collection framework provided by the other two practical classes comparable and comparator. A class is sortable, and it should implement the comparable interface . Sometimes more than one class has the same sorting algorithm, it is not necessary to define the same sorting algorithm at each separate time, as long as the comparator interface is implemented. There are two useful common classes in the collection framework: collections and Arrays. Collections provides some very useful methods for a collection container such as sorting, copying, finding, and populating, and arrays is doing a similar operation on an array.

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 (MUTABLEOBJECT) must be operated with care. If a mutable element in a set changes its state, causing Object.Equals (Object) =true will cause some problems.

===============================================

Map interface

A map is a container that associates a key object with a value object , and a value object can be a map, and so on, so that a multilevel map can be formed. For a key object, like set, a key object in a map container does not allow repetition , which is to keep the consistency of the search results, and if there are two key objects, then there is a problem when you want to get the value object corresponding to that key object, and you may not get the value object you want. The result is confusion, so the uniqueness of the key is important and conforms to the nature of the set. Of course, in the process of use, the value object corresponding to a key may change, then the last modified value object corresponds to the key. There is no unique requirement for value objects. You can map any number of keys to a value object without any problems (though it may be inconvenient for you to use it, you don't know what you get is the value object for that key). There are two more common implementations of map: HashMap and TreeMap. HashMap also uses the hash code algorithm, in order to quickly find a key, TreeMap is the key in order to store, so it has some extension methods, such as Firstkey (), Lastkey () and so on, you can also specify a range from the TreeMap to get its child map. The association of Keys and values is simple, and the pub (Object Key,objectvalue) method allows you to associate a key with a value object. Use Get (Objectkey) to get the value object corresponding to this key object.

Note thatmap 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.

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 initialcapacity and load factor two parameters. Typically, the default load factor0.75 is a good way to achieve time and space equalization. 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 (the expected GET method returns null),To avoid this problem, just keep in mind that you need to replicate both the Equals method and the Hashcode method, not just one.
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.

Differences between the Hashtable class and the HashMap class

There are three important differences between the Hashtable and the HashMap class. The first difference is mainly historical reasons. Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2.

MaybeThe most important difference is that the Hashtable method is synchronous, and the HashMap method is not。 This means that while you can use a hashtable in a multithreaded application without taking any special action, you have to do the same for aHashMap provides external synchronization. A convenient way is to use the static Synchronizedmap () method of the Collections class, it creates a thread-safe map object and returns it as a encapsulated object. The method of this object allows you to synchronize access to potential hashmap. The result is that when you don't need to sync, you can't cut off synchronization in Hashtable (like in a single-threaded application), and synchronization adds a lot of processing overhead.

The 3rd difference is that only hashmap can let you use NULL as a key or value for the entry of a table. Only one record in HashMap can be an empty key, but any number of entries can be empty value. This means that if a search key is not found in the table, or if a search key is found, but it is an empty value, then get () returns NULL. If necessary, use the Containkey () method to differentiate between the two cases.

Some information suggests thatwhen synchronization is required, use Hashtable and vice versa with HashMap。 However, because HashMap can be synchronized when needed,HashMap features more features than Hashtable, and it is not based on a stale class, so it is argued that, in all cases, HashMap takes precedence over Hashtable.

About properties
Sometimes, you might want to use a hashtable to map the string of key to the string of value. The environment strings in DOS, WINDOWS, and Unix have some examples, such as the string path of key that is mapped to the string C:\WINDOWS of value; C:\WINDOWS\SYSTEM. Hashtables is a simple way to represent these, but Java provides another way.

the Java.util.Properties class is a subclass of Hashtable, designed for string keys and values. The use of the properties object is similar to the use of Hashtable, but the class adds two time-saving methods, which you should know.

The store () method saves the contents of a Properties object to a file in a readable form. The Load () method is exactly the opposite, used to read the file and set the Properties object to contain keys and values.

Note that because properties extends the Hashtable, you can use the put () method of the superclass to add keys and values that are not string objects. This is not advisable. In addition, if you use the store () for a Properties object that does not contain a string object, store () will fail. As an alternative to put () and get (), you should use SetProperty () and GetProperty (), which use the string parameter. Reference: http://zhidao.baidu.com/question/5458097.html

===============================================

Tip

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.

The main implementation class of collection interface and map interface in Java

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.