Java Collection Class summary record-for your own knowledge point record

Source: Internet
Author: User
Tags array length constant hash set set
one, set and array

arrays , which can store basic data types, are a container for storing objects, but the lengths of the arrays are fixed and are not suitable for use when the number of objects is unknown.

The length of the


collection (which can only store objects, and object types may be different) is variable and can be used in most cases.
Second, hierarchical relationships as shown in the figure: in the figure, the solid line border is the implementation class, the polyline border is an abstract class, and the dotted 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 generated two interfaces, is set and list. A set cannot contain duplicate elements. A list is an ordered collection that can contain duplicate elements, providing a way to access them by index. The

Map is another interface in the Java.util package that has no relationship to the collection interface and is independent of each other, but is part of the collection class. The map contains key-value pairs. The map cannot contain duplicate keys, but it can contain the same value.

Iterator, all collection classes implement the Iterator interface, which is an interface used to traverse the elements in the collection, consisting mainly of the following three methods:
1.hasNext () If there is a next element.
2.next () returns the next element.
3.remove () deletes the current element. Three, several important interfaces and classes Introduction 1, List (ordered, repeatable)
The objects stored in the list are ordered, and can be repeated, the list is concerned with the index, with a series of index-related methods, query faster. Because when you insert or delete data into the list collection, it is accompanied by the movement of subsequent data, and all insertions are slow to delete data.

2, set (unordered, not repeatable)
The objects stored in the set are unordered, cannot be duplicated, objects in the collection are not sorted in a particular way, but simply add objects to the collection.

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

contrasts as follows:


Whether the

,

is orderly,

Allow elements to repeat /p>

Collection

 

 

List

is

is

Set

Abstractset

No

No

/p>

HashSet

TreeSet

Yes (with binary sort tree)

Map

Abstractmap

No

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

HashMap

TreeMap

Yes (with binary sort tree)


Four, TraverseThe following four common output modes are available in the class set:


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


2) Listiterator: Is the iterator of the interface, specifically for output list content.


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


4) for Loop


The code example is as follows:


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


Form of foreach: 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 functionality. LinkedList often used in more and more operations and query operations are very few cases, 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 key hashcode value, according to the key can directly obtain its value, with a fast access speed, traversal, the order of the data obtained is completely random. Because the key object cannot be duplicated, HashMap allows only one record key to be null, allowing multiple records to have a null value and a non synchronized


Hashtable


Hashtable, similar to HashMap, is a HashMap thread-safe version that supports thread synchronization, in which only one thread can write hashtable at any one time, thus causing Hashtale to write slowly, inheriting from the dictionary class, The difference is that it does not allow record keys or values to be null, and is less efficient.


Concurrenthashmap


Thread safe, and the lock separates. Concurrenthashmap internal use of segments (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 saves the insertion order of the records, and when traversing the Linkedhashmap with Iteraor, the first recorded record must be inserted first, and the traversal will be slower than HashMap, with all the features of HashMap.


TreeMap


TreeMap implementation of the Sortmap interface, the record it can be saved according to the key sorting, default is the key value of ascending sort (natural order), can also specify the sort of comparator, when the iterator Traverse TreeMap, the record is ordered. The key value is not allowed to be null, not synchronized;


The traversal of the map


First: Keyset ()
Stores all the keys in the map into the set collection. Because the set has an iterator. All the keys can be iterated out and then based on the Get method. Gets the corresponding value for each key. Keyset (): After iteration, you can only fetch key through get ().
The result is random, because the Hashmap.keyset () method is used when the data row primary key is obtained, and this method returns the set result, in which the data is ordered to emit.
Typical uses are 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 the keys for the map Collection, keyset ()
Iterator it = Map.keyset (). iterator ();
 Gets the iterator while
(It.hasnext ()) {
Object key = It.next ();
System.out.println (Map.get (key));
}

The second type: EntrySet ()
Set<map.entry<k,v>> EntrySet ()//returns the Set view of the mapping relationship contained in this map. (A relationship is a key-value pair), that is, a pair of (key-value) as a whole is stored in a 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 uses are as follows:
Map map = new HashMap ();
Map.put ("Key1", "Lisi1");
Map.put ("Key2", "Lisi2");
Map.put ("Key3", "Lisi3");
Map.put ("Key4", "Lisi4");
The mapping relationship in the map collection is taken out and stored in the set set
iterator it = Map.entryset (). iterator ();
while (It.hasnext ()) {
Entry e = (Entry) it.next ();
System.out.println (the value of the "key" +e.getkey () + is "+ E.getvalue ()");
}
The second approach, the EntrySet () method, is recommended for high efficiency.
For the keyset is actually traversed 2 times, one is to iterator, one is to remove the key from the HashMap value. And EntrySet just traversed the first time, it put the key and value are placed in the entry, so fast. The difference of traversal time between two kinds of traversal is still very obvious. Vii. Summary of major implementation categories
Vector and ArrayList
1,vector is thread-synchronized, so it is thread-safe, and ArrayList is thread-asynchronous and unsafe. If the thread security factor is 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. If you use data in a set that is larger than the data, vector has a certain advantage.
3, if you look for data at a given location, vectors and ArrayList use the same time, and if you visit the data frequently, use vectors and ArrayList at this time. If moving a specified position causes the subsequent elements to move, this should take into account the use of linklist, as it moves the data at a specified location without moving the other elements.
ArrayList and vectors store data in an array, which is larger than the actual stored data in order to increase and insert elements, both allow direct ordinal index elements, but the insertion of data involves the movement of array elements such as memory operations, so the index data fast, insert data slowly, Vector because of the use of the Synchronized method (thread safety), so the performance is worse than ArrayList, LinkedList use a two-way linked list to store, indexed data by ordinal need to go forward or backward traversal, but when inserting data only need to log the item before and after, So the inserts are several times faster.


ArrayList and LinkedList
1.ArrayList is a data structure based on dynamic array, LinkedList based on the data structure of the 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 more advantageous for new and delete operations because ArrayList want to move the data. This depends on the actual situation. If only the single data inserted or deleted, ArrayList speed is better than LinkedList. But if the batch random inserts deletes the data, the 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 for quick lookup, and treemap all elements are maintained in a certain order, if you need to get an orderly result you should use TreeMap (HashMap in the order of the elements are not fixed).
2, inserts, deletes and locates the element in the map, HashMap is the best choice. But if you want to iterate through the keys in natural or custom order, then TreeMap will be better. The implementation of Hashcode () and Equals () is clearly defined by the key class added using the HashMap requirement.
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;
In TreeMap, the same value map, in different order, equals, true, indicates that the treemap is sorted in the order of equals ().


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







List, Set, does map inherit from collection interface? List,set is













Collection├list│├linkedlist│├arraylist│└vector│└stack└set Map├hashtable├hashmap└weakhashmap all implementations of the Collection interface Class must provide two standard constructors: parameterless constructors are used to create an empty collection, and a constructor for a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection. The latter constructor allows the user to replicate a collection. How to traverse every element in the collection. Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that can be used to access each element of the collection one at a time. Typical usage is as follows: iterator it = Collection.iterator (); Gets an iterative child while (It.hasnext ()) {Object obj = It.next ();///Get the next element} The two interfaces derived from the collection interface are list and set.

List Interface
The list is an ordered collection, using this interface to precisely control where each element is inserted. The user can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript). Unlike the set mentioned below, the list allows the same elements. In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards. Common classes that implement the list interface are LinkedList, Arraylist,vector, and stack. The LinkedList class LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque). Note that LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list:list list = collections.synchronizedlist (new LinkedList (...)) when the list is created. The ArrayList class ArrayList implements a variable sized array. It allows all elements, including null. ArrayList is not synchronized. The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The other methods run at a linear time. Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store the elements. This capacity can automatically increase as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to increase the insertion efficiency. Like LinkedList, ArrayList is also unsynchronized (unsynchronized). Vector vectors are very similar to ArrayList, but vectors are synchronized. Iterator created by vector, though, and arrThe iterator created by Aylist is the same interface, but because vectors are synchronized, and when one iterator is created and is being used, another thread changes the state of the vector (for example, by adding or removing some elements), When the iterator method is invoked, the concurrentmodificationexception is thrown, so the exception must be caught. The Stack class stack inherits from the vector, implementing a LIFO stack. Stack provides 5 additional methods that allow vectors to be used as stacks. Basic push and Pop methods, and Peek method to get the top of the stack elements, empty method test stack is empty, the search method detects an element in the stack position. Stack is just created after stack is empty. set Interface
A set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element. Obviously, the constructor of the set has a constraint, and the incoming collection parameter cannot contain duplicate elements. Note: You must be careful to manipulate variable objects (mutable object). If a variable element in a set changes its state, causing the Object.Equals (Object) =true to cause some problems. Map Interface
Note that the map does not inherit the collection interface, and the map provides a mapping of key to value. A map cannot contain the same key, and each key can map only one value. The map interface provides a view of 3 collections, which can be treated as a set of key sets, a set of value sets, or a set of key-value mappings. The Hashtable class Hashtable inherits the map interface and implements a hash table of key-value mappings. Any object that is Non-null (non-null) can be a key or value. Adding data using put (key, value), fetching data using get (key), the time cost of these two basic operations is constant. Hashtable adjusts performance by initial capacity and load factor two parameters. Typically, the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor saves space but the corresponding lookup time increases, which can affect operations like get and put. Using Hashtable For example, put 1,2,3 into Hashtable, their key is "one", "two", "three": Hashtable numbers = new Hashtable (); Numbers.put ("One", New Integer (1)); Numbers.put ("Two", New Integer (2)); Numbers.put ("Three", New Integer (3)); To remove a number, such as 2, use the corresponding Key:integer n = (Integer) numbers.get ("two"); System.out.println ("two =" + N); Because an object that is a key will determine the location of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods. The hashcode and Equals methods inherit from the root class object, and if you use a custom class as a key, be very careful, as defined by the hash function, if two objects are the same, that is, obj1.

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.