Go Differences and linkages between the five most common collection classes in Java

Source: Internet
Author: User

There are several common types of collections:

List structure Collection class: ArrayList class, LinkedList class, Vector class, Stack class

The collection class of the map structure: HashMap class, Hashtable class

Set structure of the Set class: HashSet class, TreeSet class

A collection of queue structures: Queue interface

The difference between HashMap and Hashtable:

HashMap and Hashtable are both Java collection classes that can be used to store Java objects, which are their same point

The following are their differences:

1. Historical reasons:

Hashtable is based on the old dictionary class, HashMap is a reality of the map interface introduced by Java 1.2.

2. Synchronization:

Hashtable is synchronous , some methods in this class ensure that objects in Hashtable are thread-safe , and HashMap is asynchronous, so objects in HashMap are not thread-safe. Because the requirements of synchronization can affect the efficiency of execution, it is a good choice to use HashMap if you do not need a thread-safe combination, which avoids the unnecessary performance overhead of synchronization, and thus improves efficiency, and the programs we write generally are asynchronous, except for server-side code.

3. Value:

HashMap can let you use NULL as the key or value of an entry for a table

Hashtable is not allowed to put a null value (NULL)

The difference between ArrayList and vectors:

Both the ArrayList and the vector are Java collection classes that are used to store Java objects, which are their same point,

Difference:

1. Synchronization:

Vectors are synchronous, and some methods of this class ensure that the objects in the vector are thread-safe, while ArrayList is asynchronous, so the objects in ArrayList are not thread-safe because synchronization requirements affect the efficiency of execution. So you don't need a thread-safe collection. Then using ArrayList is a good choice to avoid unnecessary performance overhead due to synchronization.

2. Data growth:

From an internal implementation mechanism, both ArrayList and vectors use arrays to control the objects in the collection, and when you add elements to both types, if the number of elements exceeds the current length of the inner array, they need to extend the length of the internal array, Vector By default automatically increases the length of the original array, ArrayList is the original 50%, so finally you get this collection of space is always larger than you actually need, so if you want to save a lot of data in the collection, then use the vector has some advantages, Because you can avoid unnecessary resource overhead by setting the initial size of the collection.

Summarize:

1) If thread safety is required, use vector,hashtable

2) If thread safety is not required, use Arraylist,linkedlist,hashmap

3) If a key value pair is required, use the hashmap,hashtable

4) If the amount of data is large, and requires thread safety to consider vector

1. ArrayList: single element, high efficiency, more for querying

2. Vector: element single, thread safe, more for querying

3. LinkedList: Element single, multiple for insert and delete

4. HashMap: element is paired, element can be empty

5. HashTable: Element pair, thread safe, element not empty

ArrayList

The bottom layer is an object array, so the ArrayList has the advantage of fast query speed and the disadvantage of slow deletion.

At the bottom of the LinkedList is a two-way loop linked list. Each data node on this list is made up of three parts: the front pointer (pointing to the position of the previous node), the data, and the back pointer (pointing to the position of the following node). The last node's back pointer points to the front pointer of the first node, forming a loop.

The query efficiency of two-way circular linked list is low but the efficiency is high.

There is no difference in usage between ArrayList and LinkedList, but there are differences in function.

LinkedList

Often used in the case of more or less operations and few query operations: queues and stacks.

Queue: FIFO data structure.

Stack: Last-in, first-out data structure.

Note: When using stacks, it is not possible to provide a way to get the stack of elements that are not the last element.

Vector

(similar to ArrayList, the difference is that vectors are heavyweight components that use to make more resources consumed.) )

Conclusion: vector (to ensure thread safety) is used in case of concurrency considerations.

Use ArrayList without regard to concurrency (no guarantee of thread security).

Interview Experience (Knowledge point):

The parent class of the Java.util.stack (stack is stacked) is a vector. But the parent class of stack is the least of the vectors. Because the bottom of the vector is an array, and the vector has a get method (meaning it may access other elements that do not belong to the last position element, it is unsafe).

Only the push class and the Get class are used for stacks and queues.

Stack classes are not easy to use.

The implementation of the stack must be used LinkedList.

(In JAVA1.5, collection has a queue to implement queues.) )

Set-hashset Implementation class:

There is only one way to traverse a set: an iterator (interator).

Elements in HashSet are unordered (this disorder refers to the order in which data is added and subsequent permutations), and the elements are not repeatable.

In object except for Finalize (), toString (), Equals (), and Hashcode ().

The HashSet is also used as an array.

When adding objects to an array using Add (Object o), the system first hashcode the object:

int Hc=o.hashcode (); The returned hashcode is an integer value.

Int i=hc%n; (n is the length of the array), after the remainder is obtained, the remainder is used to add data to the corresponding position in the array, with N 6 as an example, if i=0 is placed in the array a[0] position, if I=1 is placed in the array a[1] position. If the value returned by Equals () is true, the data is duplicated. If Equals () returns a value of false, then the other location is compared. Such a mechanism causes two identical objects to be added to the array repeatedly, because their hashcode are different.

If we can make two identical objects with the same hashcode, we can return to true in Equals ().

In the instance, the hashcode that overrides the student object when it is defined.

Because the string class is automatically overwritten, there is no case of two identical string objects when comparing objects of the string class.

Now, in most of the JDK, Hashcode has been asked to overwrite it.

Conclusion: If you add a custom class with HashSet, be sure to overwrite hashcode () and Equals (), overriding the principle of ensuring that when two objects hashcode return the same integer, and that the Equals () return value is true.

If you are lazy and do not set equals (), it will result in the return hashcode, although the result is the same, but the execution of the program will call equals () multiple times, thus affecting the efficiency of program execution.

We want to ensure that the return of the same object hashcode must be the same, but also to ensure that the hashcode of the same object is as different as possible (because the bounds of the array, hashcode may be the same).

Example:

public int hashcode () {

Return Name.hashcode () +age;

}

This example ensures that the same name and age record returned by the hashcode are the same.

Advantages of using HashSet:

The bottom of the hashset is an array, and its query efficiency is very high. Moreover, when adding and removing, the position of the element is determined by the comparison of the hashcode used, so there is no offset of the element, so the efficiency is very high. Because HashSet queries and deletes and increases the efficiency of the elements are very high.

But the efficiency of hashset additions and deletions is through the cost of a lot of space in exchange: Because the larger the space, the remainder of the same situation is less. HashSet This algorithm creates a lot of useless space.

When using the HashSet class, be aware that if there is a conflict, there will be a case of traversing the entire array, which makes the efficiency very low.

Go Differences and linkages between the five most common collection classes 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.