Differences between ArrayList Vector sorted list, HashMap, and Hashtable

Source: Internet
Author: User

ArrayList and Vector use arrays to store data. The number of elements in the array is greater than that in the actual storage for adding and inserting elements. Both allow direct serial number index elements.

However, inserting data must be designed for memory operations such as array element movement. Therefore, index data is inserted slowly. Because the synchronized method is used for Vector (thread-safe)

Therefore, the performance is worse than that of ArrayList. The sorted list uses a two-way linked list for storage. Data indexed by serial number needs to be traversed forward or backward, but only

You only need to record the items before and after this item, so the insertion speed is faster!

Linear tables, linked lists, and hash tables are common data structures. During Java Development, JDK provides a series of corresponding classes for us to implement basic data structures. These

Classes are in the java. util package. This article attempts to explain the functions of each class and how to use these classes correctly through a simple description.

Collection
Shortlist
│ Invalid parameter list
│ ├ ArrayList
│ Vector
│ Elastic Stack
Sorted Set
Map
├ Hashtable
├ HashMap
└ WeakHashMap

Collection Interface
Collection is the most basic Collection interface. A Collection represents a group of objects, namely, Elements of the Collection ). Some collections allow

The same element, but others do not. Some can be sorted, while others cannot. Java SDK does not provide classes that directly inherit from Collection. All classes provided by Java SDK inherit from

"Sub-interfaces" of Collection, such as List and Set.
All classes that implement the Collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty Collection with one

The constructor of the Collection parameter is used to create a new Collection, which has the same elements as the imported Collection. Next Constructor

Allows users to copy a Collection.
How to traverse every element in the Collection? Regardless of the actual Collection type, it supports an iterator () method. This method returns an iteration

By using this iterator, each element in the Collection can be accessed one by one. The typical usage is as follows:
Iterator it = collection. iterator (); // obtain an Iterator
While (it. hasNext ()){
Object obj = it. next (); // obtain the next element.
}
The two interfaces derived from the Collection interface are List and Set.

List Interface
List is an ordered Collection, which can be used to precisely control the insert position of each element. You can use indexes (The position of elements in the List is similar

To access the elements in the List, which is similar to the Java array.
Unlike the Set mentioned below, the List can have the same element.
In addition to the iterator () method required for the Collection interface, List also provides a listIterator () method, returns a ListIterator interface, and

Compared with the quasi-Iterator interface, ListIterator has some add () and other methods, allowing you to add, delete, set elements, and traverse forward or backward.
Common classes that implement the List interface include the List, ArrayList, Vector, and Stack.

Sort list class
The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list.

. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ).
Note that the synchronized list method is not available. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct

Create a synchronous List:
List list = Collections. synchronizedList (new Collections List (...));

ArrayList class
ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized.
Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. When other methods are running

Is linear.
Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase as new elements are added,

However, the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve insertion efficiency.

.
Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ).

Vector
The Vector is very similar to the ArrayList, but the Vector is synchronized. Although the Iterator created by Vector is the same interface as the Iterator created by ArrayList,

However, because the Vector is synchronized, when an Iterator is created and in use, another thread changes the state of the Vector (for example, adding or deleting some

In this case, ConcurrentModificationException is thrown when the Iterator method is called. Therefore, this exception must be caught.

Stack
Stack inherits from Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. Basic push and pop

The method also has the peek method to get the elements at the top of the stack. The empty method tests whether the stack is empty. The search method checks the position of an element in the stack. After the Stack is created

Empty stack.

Set Interface
Set is a Collection that does not contain repeated elements, that is, the two elements e1 and e2 both have e1.equals (e2) = false, and Set has a maximum of null elements.
Obviously, the Set constructor has a constraint that the imported Collection parameter cannot contain repeated elements.
Note: You must be careful when operating Mutable objects ). If a variable element in a Set changes its state, the Object. equals (Object)

= True may cause some problems.

Map Interface
Note that Map does not inherit the Collection interface. Map provides the key ing between key and value. A Map cannot contain the same key, and each key can only be mapped to one

Value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing.

Hashtable class
Hashtable inherits the Map interface and implements a key-value ing hash table. Any non-null object can be used as a key or value.
Put (key, value) is used for adding data, and get (key) is used for retrieving data. The time overhead of these two basic operations is constant.
Hashtable uses the initial capacity and load factor parameters to adjust the performance. The default load factor 0.75 is usually used to balance time and space.

. Increasing the load factor can save space, but the corresponding search time will increase, which affects operations such as get and put.
A simple example of Hashtable is as follows: Put 1, 2, 3 into Hashtable, and their keys are "one", "two", and "three ":
Hashtable numbers = new Hashtable ();
Numbers. put ("one", new Integer (1 ));
Numbers. put ("two", new Integer (2 ));
Numbers. put ("three", new Integer (3 ));
To retrieve a number, such as 2, use the corresponding key:
Integer n = (Integer) numbers. get ("two ");
System. out. println ("two =" + n );
As the key object is determined by calculating its hash function, any object used as the key must implement the hashCode and

Equals method. The hashCode and equals Methods inherit from the root class Object. If you use a custom class as the key, Be careful according to the definition of the hash function, such

If the two objects are the same, that is, obj1.equals (obj2) = true, their hashCode must be the same, but if the two objects are different, their hashCode is not necessarily different.

If the hashCode of two different objects is the same, this phenomenon is called a conflict. A conflict will increase the time overhead of the Operation hash table, so we try to define the hashCode () as much as possible ()

Method to accelerate the operation of the hash table.
If the same object has different hashCode, operations on the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, only

Remember one thing: you must rewrite the equals method and hashCode method at the same time, instead of writing only one of them.
Hashtable is synchronous.

HashMap class
HashMap is similar to Hashtable. The difference is that HashMap is non-synchronous and allows null, that is, null value and null key ., However

When it is set to Collection (the values () method can return Collection), the time overhead of its iteration sub-operation is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations

Do not set the HashMap initialization capacity too high or the load factor too low.

WeakHashMap class
WeakHashMap is an improved HashMap that implements "weak references" to keys. If a key is no longer referenced by external entities, it can be recycled by GC.

Summary
If operations such as stacks and queues are involved, you should consider using the List. For elements that need to be inserted and deleted quickly, you should use the sort List.

The question element should use ArrayList.
If the program is in a single-threaded environment, or the access is only performed in one thread, the efficiency of non-synchronous classes is high. If multiple threads may operate one

Class, the synchronous class should be used.
Pay special attention to the operations on the hash table. The equals and hashCode methods should be correctly rewritten as the key object.
Try to return the interface rather than the actual type. For example, if the List is returned rather than the ArrayList, if you need to replace ArrayList with the ArrayList, the client code does not

Use Change. This is for abstract programming.

Synchronization
The Vector is synchronized. Some methods in this class ensure that the objects in the Vector are thread-safe. The ArrayList is asynchronous. Therefore

It is not thread-safe. Because the synchronization requirements will affect the execution efficiency, it is a good choice to use ArrayList if you do not need a thread-safe set.

This avoids unnecessary performance overhead due to synchronization.
Data Growth
In terms of the internal implementation mechanism, both ArrayList and Vector use arrays to control objects in the set. When you add elements to these two types

The number of elements exceeds the current length of the internal array. They all need to extend the length of the internal array. By default, the Vector automatically doubles the length of the original array.

Is the original 50%, so the space occupied by the collection in the end is always larger than what you actually need. So if you want to save a large amount of data in the collection, use

Vector has some advantages, because you can avoid unnecessary resource overhead by setting the initialization size of the set.
Usage mode
In ArrayList and Vector, it takes the same time to search for data from a specified position (through an index) or add or remove an element at the end of the set,

This time is represented by O (1. However, if an element is added or removed from another position in the Set, the time consumed will grow linearly: O (n-I), where n represents the set

Number of elements. I indicates the index position for adding or removing elements. Why? Assume that

All elements must be displaced. What does all this mean?
This means that you can only search for elements at a specific position or add or remove elements at the end of the set. You can use vector or arraylist. For other operations,

You 'd better select other set operation classes. For example, does the linklist set class take the same time to add or remove any element from the set? O (1), but it is in

The use of an index element is slow-O (I), where I is the index location. It is also easy to use arraylist, because you can simply use indexes instead of creating

Iterator object operations. Linklist also creates an object for each inserted element, and you need to understand that it also brings additional overhead.
Finally, in practical Java, Peter Haggar recommends using a simple array instead of vector or arraylist. Especially for execution

This is especially true for programs with high efficiency requirements. Array is used to avoid synchronization, additional method calls, and unnecessary Space reallocation.

Hashtable is widely used. hashmap is a class used to replace hashtable in the new framework. In other words, hashmap is recommended instead of hashtable. Maybe you

I think hashtable is very useful. Why not? Here we will briefly analyze their differences.
1. The hashtable method is synchronous, And the hashmap is not synchronized. Therefore, the difference between manual synchronization of hashmap in multithreading is like that of vector and arraylist.

2. hashtable does not allow null values (neither key nor value). hashmap allows null values (both key and value ).

3. HashTable has a contains (Object value), which has the same functions as containsValue (Object value.

4. HashTable uses Enumeration and HashMap uses Iterator.

The above is just a difference on the surface, and their implementation is also very different.

5. The default size of the hash array in HashTable is 11, and the increase is in the old * 2 + 1 mode. The default size of the hash array in HashMap is 16, and it must be an index of 2.

6. For different hash values, HashTable directly uses the hashCode of the object. The Code is as follows:
Int hash = key. hashCode ();
Int index = (hash & 0x7FFFFFFF) % tab. length;
HashMap recalculates the hash value and replaces the modulo:
Int hash = hash (k );
Int I = indexFor (hash, table. length );

Static int hash (Object x ){
Int h = x. hashCode ();

H + = ~ (H <9 );
H ^ = (h >>> 14 );
H + = (h <4 );
H ^ = (h >>> 10 );
Return h;
}
Static int indexFor (int h, int length ){
Return h & (length-1 );
}
The above are just some outstanding differences. Of course, there are many differences in their implementation, such
HashMap's null operation

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.