Java Collection Class Rollup

Source: Internet
Author: User
Tags array length set set

First, collections and arrays

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.

Ii. 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, all of the collection classes implement the Iterator interface, which is an interface for iterating through the elements in the collection, which consists 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.

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

Whether

Is

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) forLoop

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. It inherits from the dictionary class, unlike the key that it does not allow to record or the value null, and the 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 are thread-synchronized, so it is thread-safe, While ArrayList is thread-asynchronous, it is not secure. 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. The
ArrayList and vectors store data in an array, which is larger than the actual stored data in order to add and insert elements, allowing direct ordinal index elements, but inserting data involves memory operations such as array element movement, so index data is fast, data is slow to insert, 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,linedlist 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 Class Rollup

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.