JAVA Collection,

Source: Internet
Author: User

JAVA Collection,

1. Set and array

An array (which can store basic data types) is a container used to store existing objects. However, the array length is fixed and is not suitable when the number of objects is unknown.

The length of a set (only objects can be stored, and object types can be different) is variable and can be used in most cases.

2. hierarchical relationships

The Collection interface is the root interface of the Collection class. Java does not provide a direct implementation class for this interface. However, the inheritance generates two interfaces: Set and List. Set cannot contain repeated elements. A List is an ordered set that can contain duplicate elements and provides an index-based access method.

Map is another interface in the Java. util package. It has no relationship with the Collection interface and is independent of each other, but all belong to a part of the Collection class. Map contains the key-value pair. Map cannot contain duplicate keys, but can contain the same value.

Iterator, all collection classes, all implement the Iterator interface, which is an interface used to traverse elements in the Set, mainly including the following three methods:
1. Whether hasNext () has another element.
2. next () returns the next element.
3. remove () deletes the current element.

Iii. Introduction to several important interfaces and Classes

1. List (ordered and repeatable)
Objects stored in the List are ordered and can be repeated at the same time. The List focuses on the index and has a series of index-related methods, so the query speed is fast. Because data is inserted or deleted in the list set, the subsequent data is moved, and the insertion and deletion of all data is slow.

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

3. Map (key-value pairs, unique keys, and unique values)
Key-value pairs are stored in the Map set. The keys cannot be repeated, and the values can be repeated. Get the value based on the key. When traversing the map set, get the set of the key first, and traverse the set to get the corresponding value.

Comparison:

 

 

Ordered or not

Whether repeated elements are allowed

Collection

No

Yes

List

Yes

Yes

Set

AbstractSet

No

No

 

HashSet

 

TreeSet

Yes (uses a binary tree)

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 (uses a binary tree)

 

Iv. Traversal

The class set provides the following four common output methods:

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

2) ListIterator: A subinterface of Iterator, which is used to output the content in the List.

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

4) for Loop

The sample code is as follows:

For: for (int I = 0; I <arr. size (); I ++ ){...}

Foreach format: for (int I: arr ){...}

Iterator format:
Iterator it = arr. iterator ();
While (it. hasNext () {object o = it. next ();...}

V. ArrayList and rule list

There is no difference between ArrayList and rule list in usage, but there is still a difference in functionality. The distinct list is often used in the case of many Add/delete operations and few query operations, the opposite is the ArrayList.

Vi. Map set

Implementation class: HashMap, Hashtable, LinkedHashMap, and TreeMap

HashMap

HashMap is the most commonly used Map. It stores data based on the HashCode value of the key, and can directly obtain its value based on the key, with fast access speed and time elapsed, the order in which data is obtained is completely random. Because key objects cannot be repeated, HashMap allows up to one record's key to be Null and multiple records to be Null, which is not synchronous.

Hashtable

Like HashMap, Hashtable is a thread-safe version of HashMap. It supports thread synchronization. That is, at any time, only one thread can write Hashtable. This also causes Hashtale to be slow during write operations, it inherits from the Dictionary class. The difference is that it does not allow the record key or value to be null, and the efficiency is low.

ConcurrentHashMap

Thread security and lock separation. ConcurrentHashMap uses segments to represent these different parts. Each Segment is actually a small hash table and they have their own locks. As long as multiple modifications occur on different segments, they can be performed concurrently.

LinkedHashMap

LinkedHashMap stores the record insertion sequence. When Iteraor is used to traverse LinkedHashMap, the first record must be inserted first. During traversal, It is slower than HashMap and has all the features of HashMap.

TreeMap

TreeMap implements the SortMap interface, which can sort the records stored by the key. By default, It is the sort of key values in ascending order (natural order), or you can specify the sort comparator, when Iterator is used to traverse the TreeMap, the obtained records are sorted in ascending order. The key value cannot be blank or non-synchronous;

Map Traversal

First: KeySet ()
Store all the keys in the Map to the set. Because set has an iterator. All keys can be retrieved iteratively, and then obtained according to the get method. Obtains the value corresponding to each key. KeySet (): The key can only be obtained through get () after iteration.
The obtained result is out of order because the HashMap. keySet () method is used when the primary key of the Data row is obtained, and the Set result returned by this method is output out of order.
The 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 obtain the set of all keys of the map set, keyset ()

The Iterator function in Java is relatively simple and can only be moved one way:

(1) The method iterator () requires the container to return an Iterator. When the next () method of Iterator is called for the first time, it returns the first element of the sequence. Note: The iterator () method is a java. lang. Iterable interface inherited by Collection.

(2) Use next () to obtain the next element in the sequence.

(3) Use hasNext () to check whether there are any elements in the sequence.

(4) use remove () to delete the elements returned by the iterator


Iterator it = map. keySet (). iterator ();
// Get iterator (iterator is usually called a "lightweight" object because it is easy to create)
While (it. hasNext ()){
Object key = it. next ();
System. out. println (map. get (key ));
}

Type 2: entrySet ()
Set <Map. Entry <K, V> entrySet () // return the Set view of the ing contained in the ing. (A link is a key-value Pair), that is, the (key-value) as a whole one-to-one stored in the Set. Map. Entry indicates the ing relationship. EntrySet (): After iteration, you can use the e. getKey () and e. getValue () methods to obtain the key and value. The Entry interface is returned.
The 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 ");
// Retrieve the ing relationships in the map set and store them to the set.
Iterator it = map. entrySet (). iterator ();
While (it. hasNext ()){
Entry e = (Entry) it. next ();
System. out. println ("key" + e. getKey () + "is set to" + e. getValue ());
}
The second method, entrySet (), is recommended for high efficiency.
The keySet is actually traversed twice, once converted to iterator, And once retrieved the value of the key from the HashMap. However, entryset only traverses the data for the first time. It puts both the key and value in the entry, so it's faster. The time difference between the two traversal methods is quite obvious.

VII. Summary of Main Implementation differences

Vector and ArrayList
1. vector is thread-synchronous, so it is thread-safe, while arraylist is asynchronous and insecure. If thread security is not taken into account, arraylist is generally used for high efficiency.
2. If the number of elements in the set is greater than the length of the current set array, the growth rate of vector is 100% of the current array length, and that of arraylist is 50% of the current array length. If you use a large amount of data in a collection, using vector has some advantages.
3. If you look for data at a specified position, the time used by vector and arraylist is the same. If you frequently access data, you can use both vector and arraylist. If you move a specified position, the subsequent elements will be moved. In this case, you should consider using linklist because it moves data at a specified position without moving other elements.
ArrayList and Vector use arrays to store data. The number of elements in the array is greater than that in the actual storage to add and insert elements. Both allow direct serial number index elements, however, data insertion involves memory operations such as array element movement, so index data is fast and data insertion is slow. Because Vector uses the synchronized Method (thread-safe), its performance is inferior to that of ArrayList, the sort list uses a two-way linked list for storage. Data indexed by serial number needs to be traversed forward or backward. However, when inserting data, you only need to record the items before and after this item, so the insertion speed is faster.

Arraylist and rule list
1. ArrayList is a dynamic array-based data structure. The ArrayList is based on the linked list data structure.
2. for Random Access to get and set, ArrayList thinks it is better than the sorted list because the sorted list needs to move the pointer.
3. For add and remove operations, LinedList is dominant because ArrayList needs to move data. This depends on the actual situation. If only a single piece of data is inserted or deleted, the ArrayList speed is better than the sort list speed. However, if data is inserted and deleted randomly in batches, the speed of the sorted list is much higher than that of the ArrayList. Because each inserted data in the ArrayList needs to move the inserted point and all subsequent data.

HashMap and TreeMap
1. HashMap uses hashcode to quickly search its content, while all elements in TreeMap maintain a fixed order, if you need to get an ordered result, you should use TreeMap (the arrangement order of elements in HashMap is not fixed ).
2. Insert, delete, and locate elements in Map. HashMap is the best choice. However, if you want to traverse keys in the natural or custom order, it is better to use TreeMap. The key classes required to be added using HashMap clearly define the implementation of hashCode () and equals.
The elements in the two maps are the same, but the order is different, resulting in different hashCode.
Perform the same test:
In HashMap, the map of the same value has different order. In equals, the value is false;
In treeMap, the map with the same value has different order. For equals, true indicates that treeMap has sorted the order in equals.

HashTable and HashMap
1. Synchronization: Hashtable is thread-safe, that is, synchronous, while HashMap is not secure or synchronous.
2. HashMap allows the existence of a null key and multiple null values.
3. The key and value of hashtable cannot be null.

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.