Home > Java > javaTutorial > Summary of JAVA collection classes

Summary of JAVA collection classes

巴扎黑
Release: 2017-07-20 13:17:11
Original
1492 people have browsed it

1. Sets and Arrays

Array (can store basic data types) is a container used to store objects, but the length of the array is fixed and is not suitable for the number of objects. Used when unknown.

The collection (which can only store objects, and the object types can be different) has variable length and can be used in most cases.

2. Hierarchical relationship

As shown in the figure: In the figure, the solid line border is the implementation class, the polyline border is the abstract class, and the dotted line border is It is the interface

Collection interface is the root interface of the collection class. There is no direct interface for this interface in Java. Implementation class. But it was inherited to produce two interfaces, namely Set and List. Set cannot contain duplicate elements. List is an ordered collection that can contain repeated elements and provides access by index.

Map is another interface in the Java.util package. It has nothing to do with the Collection interface and is independent of each other, but they are both part of the collection class. Map contains key-value pairs. Map cannot contain duplicate keys, but it can contain the same value.

Iterator, all collection classes, implement the Iterator interface. This is an interface used to traverse elements in a collection. It mainly includes the following three methods:
1. Is there any next method in hasNext() an element.
2.next() returns the next element.
3.remove() deletes the current element.

3. Introduction to several important interfaces and classes

1. List (ordered, repeatable)
The objects stored in the List are ordered , and it is also repeatable. List focuses on indexes, has a series of methods related to indexes, and has fast query speed. Because when inserting or deleting data into the list collection, it will be accompanied by the movement of subsequent data, and all insertion and deletion of data are slow.

2. Set (unordered, cannot be repeated)
The objects stored in Set are unordered and cannot be repeated. The objects in the set are not sorted in a specific way, but the objects are simply added to the set. middle.

3. Map (key-value pairs, unique keys, non-unique values)
The Map collection stores key-value pairs. Keys cannot be repeated, but values ​​can be repeated. Obtain the value according to the key. When traversing the map collection, first obtain the set collection of the key, traverse the set collection, and obtain the corresponding value.

The comparison is as follows:

##SetAbstractSetNoNo##  Map ## 

 

 

Whether it is in order

Whether elements are allowed to be repeated

Collection

No

##Yes

List

Yes

is

HashSet

TreeSet

Yes (using a binary sorted tree)

AbstractMap

No

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

HashMap

TreeMap

is ( Use binary sorting tree)

#

4. Traversal

The following four common output methods are provided in the class set:

1) Iterator: iterative output, It is the most commonly used output method.

2) ListIterator: It is a sub-interface of Iterator, specially used to output the contents of List.

3) foreach output: a new function provided after JDK1.5, which can output arrays or collections.

4) for loop

The code example is as follows:

The form of for: for (int i=0;i

The form of foreach: for (int i: arr) {...}

The form of iterator:
Iterator it = arr.iterator();
while (it.hasNext()){ object o =it.next(); ...}

5. ArrayList and LinkedList

Usage of ArrayList and LinkedList There is no difference, but there is still a functional difference. LinkedList is often used in situations where there are many additions and deletions but few query operations, while ArrayList is the opposite.

6. Map collection

Implementation classes: HashMap, Hashtable, LinkedHashMap and TreeMap

HashMap

HashMap is the most commonly used Map, which stores data according to the HashCode value of the key, can directly obtain its value according to the key, and has a very fast access speed. When traversing, the order in which the data is obtained is completely random. Because the key object cannot be repeated, HashMap only allows the key of one record to be Null, and allows the value of multiple records to be Null, which is asynchronous

Hashtable

Hashtable is similar to HashMap, and is The thread-safe version of HashMap supports thread synchronization, that is, only one thread can write to Hashtable at any time, which also causes Hashtale to be slower when writing. It inherits from the Dictionary class, but the difference is that it does not allow recording. The key or value is null and the efficiency is low.

ConcurrentHashMap

Thread-safe and lock-separated. ConcurrentHashMap uses segments internally to represent these different parts. Each segment is actually a small hash table, and they have their own locks. Multiple modification operations can occur concurrently as long as they occur on different segments.

LinkedHashMap

LinkedHashMap saves the insertion order of records. When traversing LinkedHashMap with Iteraor, the record obtained first must be inserted first. It will be slower than HashMap during traversal. There is HashMap All features.

TreeMap

TreeMap implements the SortMap interface, which can sort the records it saves according to keys. The default is to sort by key values ​​in ascending order (natural order). You can also specify a sorting comparator. When using When the Iterator traverses the TreeMap, the records obtained are sorted. The key value is not allowed to be empty and non-synchronous;

Traversal of map

First type: KeySet()
Store all the keys in the Map into the set collection. Because set has iterators. All keys can be retrieved iteratively and then based on the get method. Get the value corresponding to each key. keySet(): After iteration, the key can only be obtained through get().
The results obtained will be out of order because when obtaining the primary key of the data row, the HashMap.keySet() method is used, and the data in the Set result returned by this method is arranged out of order.
Typical usage is as follows:
Map map = new HashMap();
map.put("key1","lisi1");
map.put("key2","lisi2");
map.put("key3","lisi3");
map.put("key4","lisi4");
//First get the set collection of all keys in the map collection, keyset ( )
Iterator it = map.keySet().iterator();
//Get the iterator
while(it.hasNext()){
Object key = it.next();
System.out.println(map.get(key));
}

Second type: entrySet()
Set> entrySet( ) //Returns the Set view of the mapping relationships contained in this mapping. (A relationship is a key-value pair), that is, (key-value) as a whole is stored in the Set collection one-to-one. Map.Entry represents the mapping relationship. entrySet(): After iteration, the key and value can be obtained by e.getKey() and e.getValue(). What is returned is the Entry interface.
Typical usage is as follows:
Map map = new HashMap();
map.put("key1","lisi1");
map.put("key2","lisi2");
map.put("key3","lisi3");
map.put("key4","lisi4");
//Take out the mapping relationship in the map set and store it in the set Set
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Entry e =(Entry) it.next();
System.out .println("key" + e.getKey () + "The value is " + e.getValue());
}
It is recommended to use the second method, the entrySet() method, which is more efficient.
The keySet is actually traversed twice, once to convert it to an iterator, and once to retrieve the value of the key from the HashMap. The entryset only traverses the first time. It puts both the key and the value into the entry, so it is faster. The difference in traversal time between the two traversals is still obvious.

7. Summary of the differences between main implementation classes

Vector and ArrayList
1. Vector is thread-synchronous, so it is also thread-safe, while arraylist is thread-asynchronous. is unsafe. If thread safety factors are not taken into consideration, it is generally more efficient to use arraylist.
2. If the number of elements in the collection is greater than the length of the current collection array, the vector growth rate is 100% of the current array length, and the arraylist growth rate is 50% of the current array length. If you use a relatively large amount of data in a collection, using vector has certain advantages.
3. If you are looking for data at a specified location, the time used by vector and arraylist is the same. If you access data frequently, you can use both vector and arraylist at this time. And if moving a specified position will cause all subsequent elements to move, you should consider using linklist at this time, because it moves the data at a specified position and other elements do not move.
ArrayList and Vector use arrays to store data. The number of array elements is larger than the actual stored data so that elements can be added and inserted. Both allow direct serial number indexing of elements, but inserting data involves memory operations such as moving array elements, so indexing The data is fast, but the data insertion is slow. Because Vector uses the synchronized method (thread safety), its performance is worse than ArrayList. LinkedList uses a doubly linked list to implement storage. Indexing data by serial number requires forward or backward traversal, but only when inserting data. You only need to record the items before and after this item, so inserting several times is faster.

arraylist and linkedlist
1.ArrayList is a data structure based on dynamic arrays, and LinkedList is a data structure based on linked lists.
2. For random access to get and set, ArrayList is better than LinkedList because LinkedList needs to move the pointer.
3. For the new and deletion operations add and remove, LinedList has the advantage because ArrayList needs to move data. This depends on the actual situation. If you only insert or delete a single piece of data, ArrayList is faster than LinkedList. But if data is randomly inserted and deleted in batches, the speed of LinkedList is much better than that of ArrayList. Because every time a piece of data is inserted into ArrayList, the insertion point and all data after it must be moved.

HashMap and TreeMap
1. HashMap uses hashcode to quickly search its content, while all elements in TreeMap maintain a certain fixed order. If you need to get an ordered result, you can TreeMap should be used (the order of elements in HashMap is not fixed).
2. To insert, delete and locate elements in Map, HashMap is the best choice. But if you want to iterate over keys in natural order or custom order, then TreeMap will be better. Using HashMap requires that the added key class clearly defines the implementation of hashCode() and equals().
The elements in the two maps are the same, but the order is different, resulting in different hashCode().
Do the same test:
In HashMap, the map of the same value is in different order, and equals is false;
In treeMap, the map of the same value is in different order, and equals is true. Note that treeMap is sorted during equals().

HashTable and HashMap
1. Synchronicity: Hashtable is thread-safe, which means it is synchronous, while HashMap is thread-safe and not synchronous.
2. HashMap allows one null key and multiple null values.
3. The key and value of hashtable are not allowed to be null.

The above is the detailed content of Summary of JAVA collection classes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template