Java collection classes

Source: Internet
Author: User
Tags array length set set

Collection Class

The collection class in the interview repeatedly test, know its importance. The collection is relative to the array, the advantages and disadvantages of the array we have long known, fixed length, support random access, not conducive to insert delete. Collection classes are built to overcome these shortcomings.

The following sections are transferred from Lipper and made some changes.

I. Hierarchical relationship

: In the figure, the solid border is the implementation class, the polyline border is an abstract class, and the point line border is the interface.

The Collection interface is the root interface of the collection class, and there is no direct implementation class in Java that provides this interface. But let it be inherited produced two interfaces, that is, set and list. The set cannot contain duplicate elements. A list is an ordered collection that can contain duplicate elements that provide a way to access by index.

Map is another interface in the Java.util package that is not related to the collection interface and is independent of each other, but is part of the collection class. Map contains the key-value pair. A map cannot contain duplicate keys, but it can contain the same value.

Iterator is a collection class that implements the Iterator interface, an interface for iterating through the elements of a collection, consisting of the following three ways:
1.hasNext () whether there is a next element.
2.next () returns the next element.
3.remove () deletes the current element.

Second, set and array

An array (which can store the base data type) is a container for storing objects, but the length of the array is fixed and not suitable for use when the number of objects is unknown.

The length of the collection (objects can only be stored and object types may be different) is variable and can be used in most cases.

The set interface is a sub-interface of the collection interface, which represents a set concept in mathematical sense. The set does not contain duplicate elements, that is, the set does not save two such elements E1 and E2, making E1.equals (E2) True. Since the data structure provided by the set interface is an abstraction of the set concept in mathematical sense, it needs to support the addition and deletion of objects without providing random access. So the set interface is the same as the collection interface, where the method is not introduced.

By definition, an Set interface inherits Collection an interface, and it does not allow duplicates to exist in the collection. All the original methods are ready-made and no new methods are introduced. The specific Set implementation class relies on the method of the added object equals() to check for equivalence.

Iii. Introduction to several important interfaces and classes

1. List (ordered, repeatable)
List of objects are ordered, but also can be repeated, list is concerned about the index, has a series of index-related methods, query fast. Since inserting or deleting data into the list collection is accompanied by the movement of the subsequent data, all insertions are slow to delete data.

2. Set (unordered, cannot repeat)
The objects stored in the set are unordered and cannot be duplicated, and the objects in the collection are not sorted in a particular way, simply by adding the object to the collection.

3. MAP (key value pair, key unique, value not unique)
The Map collection stores key-value pairs, keys cannot be duplicated, and values can be duplicated. According to the key to get the value, the map set to traverse the first get the set set of keys, the set set to traverse, to get the corresponding value.

The comparison is as follows:

 

 

is ordered

Whether elements are allowed to repeat

Collection

List

Is

Is

Set

Abstractset

Whether

Whether

 

HashSet

 

TreeSet

Yes (with binary sort tree)

Map

Abstractmap

Whether

Use Key-value to map and store data, key must be unique, value can be repeated

 

HashMap

 

TreeMap

Yes (with binary sort tree)

Four, traverse

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

1) Iterator: Iterative output, is the most used output mode.

2) Listiterator: is the sub-interface of the iterator, specifically used to output the contents of the list.

3) foreach output: A new feature provided after JDK1.5 that allows you to output an array or a collection.

4) for Loop

The code examples are as follows:

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

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

form of iterator:
Iterator it = Arr.iterator ();
while (It.hasnext ()) {object o =it.next (); ...}

V. ArrayList and LinkedList

There is no difference in usage between ArrayList and LinkedList, but there are differences in function. LinkedList often used in the case of more additions and deletions and very few query operations, ArrayList is the opposite.

Vi. Collection of Maps

Implementation classes: HashMap, Hashtable, Linkedhashmap, and TreeMap

HashMap

HashMap is the most commonly used map, it stores data according to the hashcode value of the key, can get its value directly according to the key, has the fast access speed, when traversing, obtains the data the order is completely random. Because key objects cannot be duplicated, HashMap allows a maximum of one record's key to be null, allowing multiple record values to be null, non-synchronous

Hashtable

Hashtable, like HashMap, is a thread-safe version of HashMap, which supports thread synchronization, which means that only one thread can write hashtable at any one time, so it also causes Hashtale to be slow to write, which inherits from the Dictionary class, The difference is that it does not allow logging of keys or values to be null, and is less efficient.

Concurrenthashmap

Thread-safe, and lock-separate. Concurrenthashmap Internal Use segment (Segment) to represent these different parts, each segment is actually a small hash table, they have their own locks. As long as multiple modification operations occur on different segments, they can be performed concurrently.

Linkedhashmap

Linkedhashmap Save the insertion Order of records, when traversing Linkedhashmap with Iteraor, the first record must be inserted first, the traversal will be slower than HashMap, there are all the characteristics of hashmap.

TreeMap

TreeMap implements the Sortmap interface, the ability to sort its saved records according to the key, the default is the key value of the ascending sort (natural order), you can also specify a sort of comparator, when using iterator traversal treemap, the resulting records are sorted out. The key value is not allowed to be null, non-synchronous;

Traversal of Map

First type: KeySet ()
Deposits all the keys in the map into the set collection. Because set has iterators. All of the keys can be iterated out and then based on the Get method. Gets the value corresponding to each key. KeySet (): The key can only be taken with get () after the iteration.
The result is random, because the Hashmap.keyset () method is used when the primary key of the data row is obtained, and the result of the set returned by this method is that the data is emitted in a disorderly 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");
Gets the set set of all keys for the map collection first, keyset ()
Iterator it = Map.keyset (). Iterator ();
Get iterators
while (It.hasnext ()) {
Object key = It.next ();
System.out.println (Map.get (key));
}

Second type: EntrySet ()
Set<map.entry<k,v>> EntrySet ()//Returns a Set view of the mapping relationships contained in this map. (A relationship is a key-value pair), which is to store (key-value) as a whole pair of pairs in the set set. Map.entry represents a mapping relationship. EntrySet (): After iteration you can E.getkey (), E.getvalue () Two methods to take key and value. The entry interface is returned.
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");
Takes the mapping in the map collection and deposits it into the set set
Iterator it = Map.entryset (). Iterator ();
while (It.hasnext ()) {
Entry e = (Entry) it.next ();
System.out.println ("Key" +e.getkey () + "value is" + e.getvalue ());
}
The second approach, the EntrySet () method, is recommended for high efficiency.
For keyset is actually traversed 2 times, one is to iterator, one is to remove the key from the HashMap for the value. And EntrySet just traversed the first time, it put the key and value in the entry, so fast. The traversal time between the two types of traversal is still quite obvious.

Vii. Summary of main realization class differences

Vector and ArrayList
1,vector is thread-synchronized, so it is thread-safe, and ArrayList is thread-asynchronous and unsafe. If the thread security factors are not taken into account, the ArrayList efficiency is generally higher.
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, while the ArrayList growth rate is 50% of the current array length. Vector has the advantage of using a larger amount of data in the collection.
3, if you look for data at a given location, the vectors and ArrayList use the same time, and if you frequently access the data, you can use both vectors and ArrayList. If moving a specified position causes subsequent elements to move, this should take into account the use of linklist, since it moves the data at a specified position without moving the other elements.
ArrayList and vectors are stored in an array of data, which is larger than the actual stored data in order to add and insert elements, both allow the direct ordinal index element, but the insertion of data to involve the array element movement and other memory operations, so index data fast, insert data slow, Vector because of the use of the Synchronized method (thread safety) so the performance is worse than the ArrayList, LinkedList using the two-way linked list to implement storage, indexed by ordinal data needs to be traversed forward or backward, but when inserting data only need to record the item's front and rear items, So the insertion is faster.

ArrayList and LinkedList
1.ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist feel better than LinkedList, because linkedlist to move the pointer.
3. Add and Remove,linkedlist are the dominant for new and deleted operations because ArrayList is moving the data. This point depends on the actual situation. If you insert or delete only a single piece of data, the ArrayList speed is better than LinkedList. But if bulk random insert deletes data, LinkedList speed is much better than ArrayList. Because ArrayList each insertion of data, you move the insertion point and all subsequent data.

HashMap and TreeMap
1, HashMap through the hashcode of its content to quickly find, and treemap all the elements are kept in a fixed order, if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed).
2, inserting, deleting and locating elements in map, HashMap is the best choice. But if you want to traverse the key in natural order or in a custom order, TreeMap is better. The implementation of Hashcode () and Equals () is clearly defined by the key class that is required to be added using HashMap.
The elements in the two map are the same, but the order is different, causing hashcode () to be different.
Do the same test:
In HashMap, the same value of the map, the order is different, equals, false;
And in TreeMap, the same value of the map, the order is different, equals, true, the treemap in Equals () is sorted out in order.

Hashtable and HashMap
1, synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is a line program is not secure, not synchronous.
2. HashMap allows the existence of a null key with multiple null value.
3, the Hashtable key and value are not allowed to be null.

Java collection classes

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.