Java Collection Components

Source: Internet
Author: User

Java Collection Components

Let's talk about Java's collection components.

When we use Java, we all encounter and use Java collections. Here, I will give a brief explanation and summary on the use of Java collections through my own understanding and online resources.

Java is mainly divided into three collection components: Set, List, and Map ).

Collection interface: Collection is the most basic Collection interface. It declares a common method applicable to Java collections. Both Set and List inherit Collection and Map.

 

Method of the Collection interface:

Boolean add (Object o): add an Object reference to the set

Void clear (): deletes all objects in the set, that is, they no longer hold references to these objects.

Boolean isEmpty (): determines whether the set is empty.

Boolean contains (Object o): determines whether a specified Object is referenced in a collection.

Iterartor iterator (): returns an iterator object that can be used to traverse elements in the set.

Boolean remove (Object o): deletes an Object reference from the set.

Int size (): returns the number of elements in the set.

Object [] toArray (): returns an array containing all elements in the set.

The Iterator () and toArray () methods are used for all elements of the set. The former returns an Iterator object, and the latter returns an array containing all elements in the set.

 

Set: Set is the simplest Set. Objects in the set are not sorted in a specific way and there are no repeated objects.

The Set interface mainly implements two implementation classes:

HashSet: The HashSet class uses a hash algorithm to access objects in a set. The access speed is relatively high.

TreeSet: The TreeSet class implements the SortedSet interface to sort objects in the set.

Set usage: stores object references without repeated objects

 

List: the feature of List is that its elements are stored in a linear manner, and repeated objects can be stored in the set.

The main implementation classes of the List interface include:

Vector (): An array that automatically increases. You can randomly access, insert, modify, and delete elements.

ArrayList (): indicates that the length of an array can be changed. Random Access to elements is allowed, and it is slow to insert or delete elements to ArrayList.

Linked List (): uses the Linked List Data Structure in implementation. Fast insertion and deletion, and slow access.

For random access to a List, only random elements are retrieved at a specific location. The get (int index) method of List puts back the object at the index location specified by the index parameter in the set. The subscript starts from "0. The two most basic methods for retrieving all objects in a set: the get () method of the for loop and the iterator.

 

 1 package FirstJavaWorld; 2  3 import java.util.Collection; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.Vector; 7  8 public class collector { 9     10     @SuppressWarnings("rawtypes")11     public static void main(String[] args) {12         Vector vec=new Vector();13         vec.clear();14         if (vec.isEmpty()) {15             System.out.println("vec is empty.");16         }17         for (int i=1; i<=10; i++) {18             vec.add(i);19         }20         System.out.println("vec size:" + vec.size() + " vec capacity:" + vec.capacity());21         for (int i=0; i<vec.size(); i++) {22             System.out.print(vec.get(i) + " ");23         }24         System.out.println();25         int num=100;26         vec.set(1, num);27         vec.remove(vec.size()-1);28         for (int i=0; i<vec.size(); i++) {29             System.out.print(vec.get(i) + " ");30         }31         System.out.println();32         Vector vec2=new Vector();33         int[] an={23,534,123,67,98};34         for (int i=0; i<5; i++) {35             vec2.add(an[i]);36         }37         vec.addAll(9, vec2);38         for (int i=0; i<vec.size(); i++) {39             System.out.print(vec.get(i) + " ");40         }41         System.out.println();42         vec.sort(null);43         for (int i=0; i<vec.size(); i++) {44             System.out.print(vec.get(i) + " ");45         }46         System.out.println();47         Comparator c=Collections.reverseOrder();48         vec.sort(c);49         for (int i=0; i<vec.size(); i++) {50             System.out.print(vec.get(i) + " ");51         }52     }53 }

 

Map ):

Map is a set that maps key objects and value objects. Each element of Map contains a pair of key objects and value objects. Map does not inherit from the Collection interface when retrieving elements from the Map set, as long as the key object is given, the corresponding value object is returned.

Common Map methods:

1. add and delete operations:

Object put (Object key, Object value): Add an element to the set

Object remove (Object key): deletes KEY-related elements.

Void putAll (Map t): Adds all elements from a specific image to the image.

Void clear (): deletes all mappings from the image.

2 query operations:

Object get (Object key): obtains the value related to the keyword key. Duplicate key objects are not allowed in the Map set. That is to say, the comparison results of any two key objects through the equals () method are false ., however, you can map any number of keys to the same value object at the same time.

 

List stores objects in the order they enter, without sorting or editing. Set accepts each object only once and uses its own internal sorting method (generally, you only care about whether an element belongs to the Set but not its order-otherwise, you should use the List ). Map also saves a copy of each element, but this is based on the "key". Map also has built-in sorting, so it does not care about the order of element addition. If the order of adding elements is important to you, you should use LinkedHashSet or LinkedHashMap.

Functions and methods of List

There are actually two types of List: one is the basic ArrayList, which has the advantage of random access elements and the other is the more powerful random List, which is not designed for fast random access, instead, it has a set of more general methods.

Order is the most important feature of List: it ensures that the specific sequence of elements is maintained. List adds many methods to the Collection so that you can insert and remove elements to the List (this is only recommended for using the sort List ). A List can generate ListIterator, which can be used to traverse the List in two directions, or to insert and remove elements from the List.

ArrayList: List implemented by arrays. Quick and Random Access to elements is allowed, but it is slow to insert and remove elements into the List. ListIterator should only be used to traverse the ArrayList from the forward, rather than to insert and remove elements. This is much higher than the overhead of the shortlist.

Optimize List: the sequential access is optimized, and the overhead of insert and delete to the List is not large. Random Access is relatively slow (replaced by ArrayList ). The following methods are available: addFirst (), addLast (), getFirst (), getLast (), removeFirst (), and removeLast (), these methods (not defined in any interface or base class) allow the consumer list to be used as a stack, queue, and bidirectional queue.

 

Functions and methods of Set

Set has the same interface as Collection, so there is no additional function, unlike the previous two different lists. In fact, Set is a Collection, but the behavior is different (this is a typical application of inheritance and polymorphism ideas: different behavior ). Set does not store repeated elements (it is more responsible for determining how to determine if the elements are the same)

Each element stored in the Set must be unique because the Set does not store duplicate elements. The equals () method must be defined for the element added to the Set to ensure the uniqueness of the object. Set has the same interface as Collection. The Set interface does not guarantee the order of maintenance elements.

HashSet: A Set designed for quick search. The object stored in the HashSet must define hashCode ().

TreeSet: The Set that stores the order. The bottom layer is the tree structure. It can be used to extract ordered sequences from the Set.

LinkedHashSet: query speed with a HashSet, and internal use of the linked list to maintain the order of elements (insert order ). When you use the iterator to traverse the Set, the result is displayed in the order of element insertion.

 

Functional methods of Map

The put (Object key, Object value) method adds a "value" (desired) and a "key" (key) associated with the "value" (use it for search ). The get (Object key) method returns the "value" associated with the given "key ". You can use containsKey () and containsValue () to test whether a Map contains a "key" or "value ". The standard Java class library contains several different maps: HashMap, TreeMap, LinkedHashMap, WeakHashMap, and IdentityHashMap. They all have the same basic interface Map, but the behavior, efficiency, sorting policy, saving object lifecycle and determining "key" equivalent policies are different.

Execution efficiency is a big problem of Map. Let's look at what get () is going to do, and we will understand why searching for "keys" in ArrayList is quite slow. This is where HashMap improves the speed. HashMap uses a special value called hash code to replace the slow key-to-key search. The hash code is a "relatively unique" used to represent the int value of an object. It is generated by converting certain information of the object. All Java objects can generate hash codes, because hashCode () is a method defined in the base class Object.

HashMap: Implementation of Map based on hash. The overhead of inserting and querying "key-value pairs" is fixed. You can use the constructor to set the capacity and load factor to adjust the container performance.

LinkedHashMap: similar to HashMap, but when traversing it iteratively, the order in which "key-value pairs" are obtained is the insertion order, or the least recently used (LRU) Order. It is only a little slower than HashMap. It is faster during iterative access because it uses the linked list to maintain the internal order.

TreeMap: based on the data structure of the red and black trees. When you view "keys" or "key-value pairs", they are sorted (the order is determined by Comparabel or Comparator ). TreeMap features that the results you get are sorted. TreeMap is the only Map with subMap () method. It can return a subtree.

WeakHashMap: weak key Map. objects used in Map are also allowed to be released. This is designed to solve special problems. If a reference other than map points to a key, the key can be recycled by the garbage collector.

IdentifyHashMap: Use = to replace the hash map used by equals () to compare the "key. Designed to solve special problems.

 

Summary:

Set, List, and Map are three important collection components in the Java language. It is necessary to spend a lot of time learning and mastering it, because the flexible use of these sets will be of great help to our development and data processing.

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.