Several java containers (Collection classes) You must know)

Source: Internet
Author: User

Several java containers (Collection classes) You must know)
I. Basic Concepts

Java container class libraries are used to hold objects and divide them into two different concepts:

1) Collection: a sequence of independent elements that follow one or more rules.The List must be inserted to save elements, but the set cannot have repeated elements. Queue determines the order in which objects are generated based on queuing rules (usually the same as the order in which they are inserted ).
2) Map: a key-Value Pair object that forms a pair. You can use the key to find the value.

| Collection
| Shortlist
| │-Invalid parameter list
| │-├ ArrayList
| │-Vector
| │ Elastic Stack
| Sorted Set
| │ ├ HashSet
| │ ├ TreeSet
| │ └ LinkedSet
|
|Map
├ Hashtable
├ HashMap
└ WeakHashMap

Note:1. java. util. Collection is a Collection interface.It provides common interface methods for basic operations on collection objects. The Collection interface has many specific implementations in the Java class library. The Collection interface provides a unified operation mode to maximize various specific sets.
  2. java. util. Collections is a packaging class.It contains various static polymorphism methods related to set operations. This class cannot be instantiated, just like a tool class, serving the Java Collection framework.

Ii. Collection Interface

Collection is the most basic Collection interface. A Collection represents a group of objects, namely, Elements of the Collection ). Some collections allow the same elements while others do not. Some can be sorted, while others cannot. The Java SDK does not provide classes that directly inherit from collections. The classes provided by the Java SDK are the "subinterfaces" that inherit from collections, such as List and Set.

Main method: boolean add (Object o) add an Object to the Collection boolean remove (Object o) delete the specified Object int size () returns the number of elements in the current collection boolean contains (Object o) check whether the specified object boolean isEmpty () exists in the set to determine whether the set is null Iterator iterator (). Return an Iterator boolean containsAll (Collection c) query whether the element boolean addAll (Collection c) in set c exists. add all the elements in set c to the set void clear () and delete all the elements in the Set void removeAll (Collection c) delete void retainAll (Collection c), an element in the c set from the set, and delete the elements not contained in set c from the set.
1. List Interface

List is an ordered Collection, which can be used to precisely control the insert position of each element. You can use an index (the position of an element in the List, similar to an array subscript) to access the elements in the List, which is similar to an array in Java.
Common classes that implement the List interface include the List, ArrayList, Vector, and Stack.

  1) Sort list class
The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ).

Note: The synchronized list does not have a synchronization method.If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronous List when creating a List: List list = Collections. synchronizedList (new Collections List (...));

  2) ArrayList class
ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized. Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear. Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency.

Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ). In general, you can use the two. Because of non-synchronization, the efficiency is relatively high.
If operations such as stacks and queues are involved, you should consider using the List. For elements that need to be inserted and deleted quickly, you should use the random List. If you need to quickly access elements randomly, you should use the ArrayList.

  3) Vector class
The Vector is very similar to the ArrayList, but the Vector is synchronized. Although the Iterator created by Vector is the same interface as the Iterator created by ArrayList, because Vector is synchronous, when an Iterator is created and in use, another thread changes the Vector State (for example, adding or deleting some elements). When calling the Iterator method, ConcurrentModificationException is thrown. Therefore, this exception must be caught.

  4) Stack class
Stack inherits from Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. The basic push and pop methods include the peek method to get the elements at the top of the stack. The empty method tests whether the stack is empty. The search method checks the position of an element in the stack. The Stack is empty after being created.

2. Set Interface

Set is a Collection that does not contain repeated elements, that is, the two elements e1 and e2 both have e1.equals (e2) = false, and Set has a maximum of null elements. The Set constructor has a constraint that the imported Collection parameter cannot contain duplicate elements.
Set containers mainly include HashSet and TreeSet.
  
  1) HashSet class
The Java. util. HashSet class implements the Java. util. Set interface.
-> Repeated elements are not allowed;
-> The sequence of elements in the political set is not guaranteed.
-> An element with a null value can be contained, but a maximum of one null element is allowed.

Public class TestHashSet {public static void main (String [] args) {HashSet h = new HashSet (); h. add (1st); h. add (2nd); h. add (new Integer (3); h. add (new Double (4.0); h. add (2nd); // duplicate element, not added h. add (new Integer (3); // duplicate element, not added h. add (new Date (); System. out. println (START: size = + h. size (); Iterator it = h. iterator (); while (it. hasNext () {Object o = it. next (); System. out. println (o);} h. remove (2nd); System. out. println (after removing the element: size = + h. size (); System. out. println (h );}}

  2) TreeSet
TreeSet describes a variant of Set-a Set that can implement sorting and other functions, when an object element is added to a set, it is automatically inserted into an ordered Object Sequence according to a comparison rule, make sure that the read uixiangxulie composed of the collection elements are arranged in ascending order.

public class TestTreeSet{    public static void main(String [] args)    {       TreeSet ts=new TreeSet();       ts.add(orange);       ts.add(apple);       ts.add(banana);       ts.add(grape);       Iterator it=ts.iterator();       while(it.hasNext())       {           String fruit=(String)it.next();           System.out.println(fruit);       }    }}
2. Map set Interface

Map does not inherit the Collection interface. Map provides the key ing from key to value. A Map cannot contain the same key, and each key can only Map one value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing.

Main method: boolean equals (Object o) Compare Object boolean remove (Object o) delete an Object put (Object key, Object value) add key and valueHashtable class

1. Hashtable class
Hashtable inherits the Map interface and implements a key-value ing hash table. Any non-null object can be used as a key or value. ** Put (key, value) is used to add data and get (key) is used to retrieve data. The time overhead of these two basic operations is constant. ** Hashtable uses the initial capacity and load factor parameters to adjust the performance. Generally, the default load factor 0.75 achieves a better balance between time and space. Increasing the load factor can save space, but the corresponding search time will increase, which affects operations such as get and put.

As the key object is determined by calculating its hash function, any object used as the key must implement the hashCode and equals methods. The hashCode and equals Methods inherit from the root class Object. If you use a custom class as the key, be very careful. According to the definition of the hash function, if the two objects are the same, that is, if obj1.equals (obj2) = true, their hashCode must be the same, but if two objects are different, their hashCode is not necessarily different. If the hashCode of two different objects is the same, this phenomenon is called a conflict. A conflict will increase the time overhead for operating the hash table. Therefore, the hashCode () method should be defined as much as possible to speed up the operation of the hash table.

If the same object has different hashCode, operations on the hash table will produce unexpected results (the expected get method returns null). To avoid this problem, you only need to remember one: the equals and hashCode methods must be rewritten at the same time, instead of writing only one of them.

2. HashMap class
HashMap is similar to Hashtable. The difference is that HashMap is non-synchronous and allows null, that is, null value and null key. However, when HashMap is treated as a Collection (values () method, the Collection can be returned ), its iteration sub-operation time overhead is proportional to the capacity of HashMap. Therefore, if the performance of iterative operations is very important, do not set the HashMap initialization capacity too high or the load factor too low.

-JDK1.0 introduces the first associated collection classHashTable, Which is thread-safe. All methods of HashTable are synchronized.
-JDK2.0 introduces HashMap, which provides an unsynchronized base class and a synchronous package synchronizedMap. SynchronizedMap is calledConditional thread security.
-Introduced in the JDK5.0util. concurrent packageConcurrentHashMap for Map thread securityIt provides higher flexibility than synchronizedMap. Concurrent read and write operations can be performed concurrently.

Differences between HashTable and HashMap

1. inheritance is different. Public class Hashtable extends Dictionary implements Map public class HashMap extends actmap implements Map 2. Methods in Hashtable are synchronized, while methods in HashMap are not synchronized by default. Hashtable can be used directly in a multi-thread concurrent environment, but you need to add synchronization to use HashMap. Third, in Hashtable, keys and values do not allow null values. In HashMap, null can be used as a key. Such a key has only one; one or more keys can correspond to null values. When the get () method returns a null value, it can indicate that the key does not exist in HashMap or that the corresponding value of the key is null. Therefore, the get () method cannot be used to determine whether a key exists in the HashMap. Instead, the containsKey () method should be used to determine whether a key exists in the HashMap. Fourth, the internal implementation of the two traversal methods is different. Hashtable and HashMap both use Iterator. For historical reasons, Hashtable also uses the Enumeration method. Fifth, the use of hash values is different. HashTable directly uses the hashCode of the object. HashMap recalculates the hash value. 6. Hashtable and HashMap are two internal implementation methods: the initial size of the array and the expansion method. In HashTable, the default size of the hash array is 11, and the increment is old * 2 + 1. The default size of the hash array in HashMap is 16, and it must be an index of 2.

3. WeakHashMap class
WeakHashMap is an improved HashMap that implements "weak references" to keys. If a key is no longer referenced by external entities, it can be recycled by GC.

 

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.