Summary of list set map in Java

Source: Internet
Author: User
Tags comparable

1. collection list set map difference memory

These represent the set in Java. Here, we mainly analyze whether its elements are ordered and whether they can be repeat for different memory for proper use. Of course, there are still synchronization differences, see the previous article.

 

 

Ordered or not

Allow repeated Elements

Collection

No

Yes

List

Yes

Yes

Set

Abstractset

No

No

Hashset

Treeset

Yes (Binary Tree sorting)

Map

Abstractmap

No

Use Key-value to map and store data. The key must be unique and the value can be repeated.

Hashmap

Treemap

Yes (Binary Tree sorting)

 

The list interface is used to expand the collection. Its specific implementation classes are commonly used arraylist and javaslist. You can put everything in a list container and retrieve it as needed. Arraylist can be seen from its name that it is stored in an array-like form, so its random access speed is extremely fast, and the internal implementation of the arraylist is a linked list, it is suitable for frequent insert and delete operations in the center of the linked list. You can select an application as needed. The iterator mentioned above can only traverse the container forward, while the listiterator inherits the iterator idea and provides a bidirectional Traversal method for the list.

The Set interface is also an extension of the collection, but different from the list, the object elements in the set cannot be repeated, that is, you cannot put the same thing twice into the same set container. Its common implementations include the hashset and treeset classes. Hashset can quickly locate an element, but you need to implement the hashcode () method for the objects you put into the hashset. It uses the hash code algorithm mentioned above. Treeset stores the elements in the Set in order, which requires that the objects in the set are sortable. This uses the other two aggregation classes comparable and comparator provided by the set framework. A class can be sorted, and it should implement the comparable interface. If multiple classes have the same sorting algorithm, you do not need to define the same Sorting Algorithm for each class. You only need to implement the comparator interface. There are two useful public classes in the Collection framework: collections and arrays. Collections provides some useful methods for sorting, copying, searching, and filling a collection container. arrays performs similar operations on an array.

Map is a container that associates key objects and value objects, and a value object can be a map, and so on. In this way, a multi-level ing can be formed. For key objects, similar to set, key objects in a map container are not allowed to be repeated to maintain consistency of the search results. If there are two key objects, the problem occurs when you want to get the value object corresponding to the key object. Maybe what you get is not the value object you want, and the result will be messy, therefore, the uniqueness of keys is very important and also conforms to the set nature. Of course, during use, the value object corresponding to a key may change. At this time, the modified value object will correspond to the key. There is no uniqueness requirement for value objects. You can map any number of keys to a value object without any problems (however, it may cause inconvenience to your use, you don't know whether you get the value object corresponding to that key ). MAP has two common implementations: hashmap and treemap. Hashmap also uses the hash algorithm to quickly find a key. treemap stores the key in order, so it has some extended methods, such as firstkey (), lastkey (), etc. You can also specify a range from the treemap to obtain its submap. The association between keys and values is very simple.
Key, object Value) method to associate a key with a value object. You can use get (Object key) to obtain the value object corresponding to this key object.

2. Differences and relationships between list, vector, set, and map

When using Java, we all encounter collections. However, Java APIs provide multiple collections, I frequently encounter this "choice" during use and interview ". :) (Mainly during the interview)
Over time, I have a little bit of experience and written it for discussion.
In general, the collection classes used in Java APIs all implement the collection interface. Its class inheritance structure is as follows:

Collection <-- list <-- Vector
Collection <-- list <-- arraylist
Collection <-- list <-- items list
Collection <-- set <-- hashset
Collection <-- set <-- hashset <-- revoke hashset
Collection <-- set <-- sortedset <-- treesetvector: array-based list, in fact, encapsulates some functions not available in array for our convenience, it cannot go into the restrictions of array. The performance cannot surpass array. Therefore, when possible, we need to use array more. Another important point is the vector "sychronized", which is the only difference between vector and arraylist.

Arraylist: Like a vector, it is an array-based linked list, but the difference is that arraylist is not synchronized. Therefore, the performance is better than that of vector, but when running in a multi-threaded environment, you need to manage the synchronization of threads on your own.

Sort list: the sort list is different from the previous two lists. It is not based on array, so it is not limited by Array Performance. Each node contains two aspects: 1. Data of the node itself; 2. Information of the next node (nextnode ). Therefore, when you add a consumer list and delete it, you do not need to move a large amount of data like an array-based list. You only need to change the relevant information of nextnode. This is the advantage of listing.

List summary:

1. All lists can only contain tables composed of a single object of different types, rather than key-value pairs. Example: [Tom, 1, C];

2. All lists can have the same elements. For example, the vector can have [Tom, koo, too, koo];

3. All lists can have null elements, such as [Tom, null, 1];

4. array-based list (vector, arraylist) is suitable for queries, while sorted list (linked list) is suitable for adding and deleting operations.

Hashset: Although set and list all implement the collection interface, their implementation methods are quite different. List is basically based on array. However, set is implemented based on hashmap, which is the fundamental difference between set and list. The hashset storage method uses the key in hashmap as the corresponding storage item of the set. Look at the add (Object
OBJ.

Public Boolean add (Object OBJ)
{
Return map. Put (OBJ, present) = NULL;
}
This is also the root reason why repeated items cannot be found in the set as in the list, because the key of hashmap cannot be duplicated.

Linkedhashset: a subclass of hashset, a linked list.

Treeset: a subclass of sortedset. Unlike hashset, treeset is ordered. It is implemented through sortedmap.

Set summary:

1. Set is implemented based on map (hashmap );

2. the elements in the set cannot be repeated. If you use the add (Object OBJ) method to add an existing object, the existing object will be overwritten; 3. java basic concepts: Collection class list/set/map... differences and connections

Collection: List, Set
Map: hashmap, hashtable

How to select between them


I. array, Arrays

Array is the most efficient method for Java's "Storage and random access to a series of objects.

1,
High efficiency, but the capacity is fixed and cannot be changed dynamically.
Another disadvantage of array is that it cannot determine the actual number of elements in the array. length only tells us the array capacity.

2. There is an arrays class in Java that is used to operate arrays.
Arrays has a set of static functions,
Equals (): checks whether two arrays are equal. Array has the same number of elements, and all corresponding elements are equal to each other.
Fill (): Enter the value in array.
Sort (): used to sort arrays.
Binarysearch (): Search for elements in the sorted array.
System. arraycopy (): copying an array.


Ii. Collection and map

If you do not know how many objects are needed when writing a program and need to automatically expand the capacity when the space is insufficient, you need to use the container class library. array is not applicable.

1. Differences between collection and map

The number of elements stored in each container is different.
Collection type, each location has only one element.
Map type, holding key-value pair, like a small database.

2. subcategories

Collection -- list: stores elements in a specific order. Therefore, the order obtained may be different from the order placed.
-- Arraylist/repeated list/vector -- set: duplicate elements cannot be contained.
-- Hashset/treeset
Map
-- Hashmap
-- Hashtable
-- Treemap

3. Other features

* List, set, and map objects are regarded as object types.
* Collection, list, set, and map are all interfaces and cannot be instantiated.
The arraylist, vector, hashtable, and hashmap inherited from them are concrete classes, which can be instantiated.
* The vector container knows exactly the type of the object it holds. Vector does not perform boundary check.


Iii. Collections

Collections is a help class for the Collection class. Provides a series of static methods for searching, sorting, and thread-based operations on various sets.
It is equivalent to arrays, a class that performs similar operations on arrays.
For example, collections. Max (Collection Coll); obtains the largest element in Coll.
Collections. Sort (list); sorts the elements in the list.

4. How to choose?

1. Differences between the container class and array
* The container class can only hold the object reference (pointer to the object), instead of copying the object information to a certain position in the series.
* Once an object is placed in a container, the type information of the object is lost.

2,
* Among various lists, it is best to use arraylist as the default choice. Use the sort list () When insertion or deletion is frequent ();
Vector is always slower than arraylist, so avoid using it whenever possible.
* In various sets, hashset is generally better than hashtree (insert and search ). Treeset is used only when a sorted sequence is generated.
The only reason for the existence of hashtree is that it can maintain the sorting status of its elements.
* In various maps
Hashmap is used for quick search.
* When the number of elements is fixed, array is used because the array efficiency is the highest.

Conclusion: arraylist, hashset, hashmap, and array are commonly used.


Note:

1. collection does not have the get () method to obtain an element. You can only use iterator () to traverse elements.
2. Set and collection have the same interface.
3. list. You can use the get () method to retrieve an element at a time. Use numbers to select one of a bunch of objects, get (0 ).... (Add/get)
4. arraylist is generally used. Use the queue list to construct the stack and queue.

5. Map uses put (K, v)/get (K) and containskey ()/containsvalue () to check whether a key/value exists.
Hashmap uses the hashcode of the object to quickly find the key.
* The hashing hash code transforms the object information to form a unique int value, which is stored in an array.
We all know that the array search speed is the fastest in all storage structures. Therefore, the search can be accelerated.

When a collision occurs, let the array point to multiple values. That is, an orders table is generated at each position of the array.

6. Elements in map can be extracted separately from the key sequence and value sequence. Use keyset () to extract the key sequence and generate a set for all the keys in the map.
Use values () to extract the value sequence and generate a collection for all values in the map.

Why does one generate a set and one generate a collection? That's because the key is always unique and the value can be repeated.

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.