Home  >  Article  >  Java  >  What are the differences between Java's Collection and Map?

What are the differences between Java's Collection and Map?

WBOY
WBOYforward
2023-05-15 22:58:041286browse

Collection interface

Collection is the most basic collection interface. A Collection represents a group of Objects, that is, the elements of the Collection. Some Collections allow identical elements and others do not. Some sort and others don't. The Java SDK does not provide classes that directly inherit from Collection. The classes provided by the Java SDK are all "sub-interfaces" that inherit from Collection, such as List and Set.

All classes that implement the Collection interface must provide two standard constructors: the parameterless constructor is used to create an empty Collection, and the constructor with a Collection parameter is used to create a new Collection. This new Collection has the same elements as the passed Collection. The latter constructor allows the user to copy a Collection.

How to traverse each element in Collection? Regardless of the actual type of Collection, it supports an iterator() method, which returns an iterator that can be used to access each element in the Collection one by one. Typical usage is as follows:

Iterator it = collection.iterator(); // Get an iterator
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

List is an ordered Collection. Using this interface, you can precisely control the insertion position of each element. Users can access elements in the List using the index (the position of the element in the List, similar to an array subscript), which is similar to Java's array.

Unlike the Set mentioned below, List allows the same elements.

In addition to the iterator() method necessary for the Collection interface, List also provides a listIterator() method, which returns a ListIterator interface. Compared with the standard Iterator interface, ListIterator has more add() and the like. Methods allow adding, deleting, setting elements, and traversing forward or backward.

Commonly used classes that implement the List interface are LinkedList, ArrayList, Vector and Stack.

LinkedList class

LinkedList implements the List interface and allows null elements. In addition, LinkedList provides additional get, remove, and insert methods at the head or tail of LinkedList. These operations allow LinkedList to be used as a stack, queue, or deque.

Note that LinkedList has no synchronization method. If multiple threads access a List at the same time, they must implement access synchronization themselves. One solution is to construct a synchronized List when creating the List:

List list = Collections.synchronizedList(new LinkedList(...));

ArrayList Class

ArrayList implements a variable-sized array. It allows all elements, including null. ArrayList is not synchronized.

size, isEmpty, get, set method running time is constant. However, the cost of the add method is an amortized constant, and adding n elements requires O(n) time. Other methods have linear running time.

Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store elements. This capacity increases automatically as new elements are added, but the growth algorithm is not defined. When a large number of elements need to be inserted, the ensureCapacity method can be called to increase the capacity of the ArrayList before inserting to improve insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized.

Vector class

Vector is very similar to ArrayList, but Vector is synchronized. Although the Iterator created by Vector has the same interface as the Iterator created by ArrayList, because Vector is synchronized, when an Iterator is created and is being used, another thread changes the state of the Vector (for example, adding or removing some element), ConcurrentModificationException will be thrown when calling the Iterator method, so the exception must be caught.

Stack class

Stack inherits from Vector and implements a last-in-first-out stack. Stack provides 5 additional methods that allow Vector to be used as a stack. The basic push and pop methods, as well as the peek method, get the element on the top of the stack, the empty method tests whether the stack is empty, and the search method detects the position of an element in the stack. Stack is an empty stack after it is created.

Set interface

Set is a Collection that does not contain repeated elements, that is, any two elements e1 and e2 have e1.equals(e2)= false, Set has at most one null element.
Obviously, the Set constructor has a constraint that the passed-in Collection parameter cannot contain duplicate elements.
Please note: Mutable Objects must be handled with care. If a mutable element in a Set changes its state causing Object.equals(Object)=true, it will cause some problems.

Map interface

Please note that Map does not inherit the Collection interface. Map provides key to value mapping. A Map cannot contain the same key, and each key can only map one value. The Map interface provides three kinds of set views. The content of the Map can be regarded as a set of key sets, a set of value sets, or a set of key-value mappings.

Hashtable class

Hashtable inherits the Map interface and implements a hash table of key-value mapping. Any non-null object can be used as key or value.
To add data, use put(key, value), and to remove data, use get(key). The time cost of these two basic operations is constant.

Hashtable adjusts performance through two parameters: initial capacity and load factor. Usually the default load factor 0.75 achieves a better balance of time and space. Increasing the load factor can save space but the corresponding search time will increase, which will affect operations like get and put.

A simple example of using Hashtable is as follows. Put 1, 2, and 3 into the Hashtable, and their keys are "one", "two", and "three" respectively:
Hashtable numbers = new Hashtable();
numbers.put(“one”, new Integer(1));
numbers.put(“two”, new Integer(2));
numbers.put(“three ”, new Integer(3));

To retrieve a number, such as 2, use the corresponding key:

Integer n = (Integer)numbers.get( "two");
System.out.println("two = " " n);

Since the object as the key will determine the corresponding value by calculating its hash function location, so any object used as a 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 a key, be very careful. According to the definition of the hash function, if the two objects are the same, that is, obj1.equals(obj2)=true, then 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. The conflict will cause the time overhead of operating the hash table to increase. Therefore, try to define a well-defined hashCode() method to speed up hash table operations.
If the same object has different hashCode, the operation of the hash table will have unexpected results (the expected get method returns null). To avoid this problem, you only need to remember one thing: override the equals method and hashCode method instead of just writing one of them. Hashtable is synchronous.

HashMap class

HashMap is similar to Hashtable, except that HashMap is asynchronous and allows null, that is, null value and null key. , but when treating HashMap as a Collection (the values() method can return a Collection), the time overhead of its iteration sub-operations is proportional to the capacity of the HashMap. Therefore, if the performance of iterative operations is important, do not set the initial capacity of HashMap too high or the load factor too low.

WeakHashMap class

WeakHashMap is an improved HashMap, which implements a "weak reference" to the key. If a key is no longer referenced externally, then the key Can be recycled by GC.

The above is the detailed content of What are the differences between Java's Collection and Map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete