Java Collection class 1

Source: Internet
Author: User
Tags array sort comparable

If the program has a limited number of objects and its lifetime is known, the program is quite simple.

Array
Arrays differ from other containers in three aspects: efficiency, type recognition, and primitives. Arrays are provided by Java and are the most efficient method for randomly storing and accessing the reference sequence. An array is a simple linear sequence that allows you to quickly access its elements. However, the speed is costly. When you create an array, its capacity is fixed and cannot be changed in its lifecycle. Maybe you will propose to create an array first, and then create a new one when it is not enough, and then export all the references in the old array to the new one. In fact, this is what arraylist will do later. However, the overhead brought by this flexibility makes arraylist effective.
The rate is significantly lower than the array.
Java performs a boundary check on both arrays and containers. If the boundary is exceeded, it returns a runtimeexception. This exception indicates that this error is caused by a programmer, so that you do not need to check it in the program.

Some generic container classes include list, set, and map. They process objects as if they do not have their own specific types. That is to say, the container regards all the elements contained in the object as (the root class of all classes in Java. In this way, you only need to create a container to put all types of objects into it. From this point of view, this approach is very good (only suffering from primitive. If it is a constant, you can also use Java's primitive Wrapper class; if it is a variable, it can only be placed in your own class ). Compared with other generic storages, the second advantage of arrays is: When an array is created, you also specify the type of the object it holds (this leads to the third point-the array can hold primitives, while
). That is to say, it will perform a type check during compilation to prevent you from inserting objects of the wrong type, or you may mistakenly type the objects during object extraction. Java can prevent you from passing an inappropriate message to an object during compilation and running. This does not mean that there is any danger when using containers. If the compiler can help you specify the program, the program runs faster and the end user will receive less harassment from program running exceptions.

From the perspective of efficiency and type check, array is always correct. However, if you are solving a more general problem, the array will look too weak.

Array is the object of the first stream.
No matter what type of Array you use, the array identifier is actually a reference for "creating real objects in heap. In fact, the object holds the reference of another object. You can use the array initialization statement to implicitly create this object. You can also use the new expression to explicitly create this object. the read-only Length attribute tells you how many elements the array can store. It is a part of an array object (actually the only property or method you can access ). The '[]' syntax is another way to access array objects.

You can't know how many elements are put in the array, because length only tells you how many elements can be put in the array, that is, the size of the array object, rather than the number of actually held elements. However, when an array object is created, its reference is automatically initialized to null, so you can check whether a "slot" of the array is null, to determine whether it holds the object. Similarly, the primitive array automatically initializes the number to zero, the character is initialized to (char) 0, and the Boolean value is initialized to false.

Primitive container
The container class can only hold the reference of the object. In addition to Objects Reference, Arrays can also directly hold primitive. Of course, wrapper classes such as integer and double can be used. Put the primitive value in the container, which is a little strange. In addition, primitive arrays are much more efficient than wrapper containers.

Of course, if you still need the flexibility of the "automatically scalable as needed" container class when using primitive, you cannot use arrays. You can only use containers to store primitive Wrapper Classes.

Returns an array.
Suppose you write a method, and it returns not one but a group of things. In Java, "an array" can be returned ". Unlike C ++, you never have to worry about the Java array-As long as you still need it, it will remain; once you have used up, the garbage collector will help you clean it.

Arrays class
Java. util contains an arrays class, which includes a set of static methods that can be used for arrays. These methods are some practical tools. There are four basic Methods: To compare the equals () of two arrays; To fill the fill (); to sort the array sort (); and binarysearch () used to search for elements in a sorted array (). All these methods overload primitive and object. In addition, there is an aslist () method that accepts an array and converts it into a list container.

Although arrays is still useful, its functions are incomplete. For example, if it allows us to print arrays directly without having to write a for loop, that's fine. In addition, as you can see, fill () can only fill in an array with one value. Therefore, fill () is powerless if you want to add the numbers that are generated immediately to the array.

Copy an array
The Java Standard Library provides a static method of system. arraycopy. Compared with the for loop, it can copy arrays at a faster speed. System. arraycopy () is overloaded for all types.

Both the object array and the primitive array can be copied. However, if you copy an object array, you only copy their reference-the object itself will not be copied. This is used as a shallow copy ).

Array comparison
To compare whether the array is completely equal, arrays provides the overloaded equals () method. Of course, it is also for a variety of primitive and object. To make the two arrays completely equal, they must have the same number of elements, and each element of the array must be equal to the element at the corresponding position of the other array. Use equals () to determine an equal surname of an element. (For primitive, it uses equals () of its Wrapper class; for example, int uses integer. Equals ().).

Array Element comparison
There are two methods in Java that allow you to implement comparative functions. First, implement the java. Lang. Comparable interface and use this method to implement the "self-contained" comparison method of the class. This is a very simple interface, and it only has one method compareto (). This method can take another object as a parameter. If the existing object is smaller than the parameter, it returns a negative number. If the existing object is the same, it returns zero. If the existing object is larger than the parameter, it returns a positive number.

The static randint () method generates a positive number between 0 and 100.
Now, someone will give you a class that does not implement the comparable interface, or this class implements the comparable interface, but you find that it does not work as expected, so we need to redefine a new comparison method. Java does not require you to insert the comparison code into the class. Its solution is to use "strategy design pattern )". With the policy, you can encapsulate the changed code into its own class (the so-called strategy object ). You give the policy object to the code that does not change, and then use it to complete the entire algorithm. In this way, you can use different policy objects to represent different comparison methods, and then give them
The same sorting program. Next we need to define the policy object by implementing the comparator interface. This interface has two methods: Compare () and equals (). However, except for special performance requirements, you do not need to implement equals (). As long as it is a class, it is implicitly inherited from the object, and the object already has an equals. Therefore, you can use the equals () of the default object to meet the interface requirements.

In the collections class, there is a comparator that will return the opposite of the object's proprietary comparative method. It can be easily used on comptype.
Collections. reverseorder () returns a comparator reference.
The compare () method returns a negative integer, zero, or positive integer based on whether the first parameter is smaller than, equal to, or greater than the second parameter.

Sorting of Arrays
With the built-in sorting method, you can sort any array, whether primitive or object array, as long as it implements the comparable interface or has a related comparator object.

The sorting algorithm used by the java standard library has been optimized-for primitive, it uses "Quick Sort", for objects, it uses "stable merge sort )". So unless prolier indicates that the sorting algorithm is a bottleneck, you don't have to worry about performance.

Query ordered arrays
Once the array is sorted, you can use arrays. binarysearch () for quick query. However, do not use binarysearch () for an unordered array, because the result is meaningless.

If arrays. binarysearch () is found, it returns a value greater than or equal to 0. Otherwise, it returns a negative value, which indicates which value should be inserted if you manually maintain the array. The value is:

-(Insert point)-1
The "insert point" is the subscript of the smallest value in all values that are greater than the value to be searched, or if all values in the array are smaller than the value to be searched, it is. size ().
If the array contains repeated elements, it cannot guarantee which one will be returned. This algorithm does not support repeated elements, but it does not report an error. Therefore, if you need an ordered sequence with no repeated elements, you can consider using the treeset described later in this chapter (support for [sorting order "sorted order "]) and linkedhashset (the insert sequence "sorted order" is supported "]). These two classes will help you look after all the details. Only when you encounter performance bottlenecks should you replace these two classes with manually maintained arrays.

If comparator is used for sorting (for object arrays, comparator is not allowed for primitive arrays, you must also use the same comparator (the reload version using this method ).

Summary of the array Section
All in all, if you want to hold a group of objects, the first choice and the most efficient choice should be array. In addition, if this is a set of primitive, you can only use arrays. There are also some more general situations, that is, when writing a program, you do not know how many objects to use, or you need to use a more complex way to store objects. Therefore, Java provides the container class )". Its basic types include list, set, and map.

They also have some other features. For example, if all the objects held by set are different, map is an "associative array", which can establish a connection between two objects. In addition, unlike arrays, they can be automatically adjusted, so you can place any number of objects in them.

Container Overview
Java2 redesigned the poorly performing container class in 1.0 and 1.1. The new design is more compact and reasonable. At the same time, it also complements the functions of the container class library, and provides the functions of the Chain List, queue, and two-way Queue (deques, read as "decks") data structures.

Java2's container class solves the problem of "how to hold objects", and it divides the problem into two categories:
1. Collection: A group of regular independent elements. List must hold these elements in a specific order, while set cannot store duplicate elements. (Bag does not have this restriction, but Java's container class library does not implement it, Because list already provides this function)

2. Map: A group of pair s that appear in the form of "key-value. At first glance, it should be a pair collection, but if we do so, it will become funny, so it is better to list this concept independently. To put it back, it is very convenient to create a collection when map itself is used. Map can return "key" set, value collection, or pair set. Like arrays, map can be easily extended to multiple dimensions without any modifications. You only need to set the MAP value to map (and then its value to map, and so on ).

Java container classes are divided into two basic types. The difference is how many objects can be placed at each location. Collection allows only one object to be put on each location (this name is a bit incorrect, because the container class library is often referred to as collections ). It includes a list of "holding a group of objects in a certain order" and a set of "only allow adding non-repeated objects. Arraylist is a list, while hashset is a set. You can use the add () method to add objects to the collection.

Map stores pair in the form of "key-value", which is like a micro-database.
MAP is also called the associative array ). You can use the put () method to add elements to the map. It accepts the key-value form pair as the parameter.
The fill () method is also overloaded for collection and map. The tostring () method of the container class is used by default. The printed collection is enclosed by square brackets, and elements are separated by commas. MAP is enclosed in curly brackets, and keys and values are associated with equal signs (keys on the left and values on the right ).

The list will hold all the objects you input honestly without sorting or editing. Set, each object is accepted only once, and elements must be re-ordered using its own rules (generally, all you care about is that the Set package does not include an object, instead of where it is-if so, you 'd better use list ). While map does not receive repeated pair, so it is not repeated. It is determined by the key. In addition, it also has its own internal sorting rules and will not be affected by the input order. If the insertion sequence is important, you can only use linkedhashset or linkedhashmap.

Fill container
Like arrays, collection also has a helper class called collections, which contains some static utility methods, including a fill (). This fill () only copies the reference of the same object to the entire container, and it can only work for list, not set and map.

Disadvantages of containers: Unknown Object Types
The disadvantage of Java containers is that when an object is put in the container, the object type information is lost. This is because developers of the container class will not know what type of objects you want to use to save, and allowing containers to only save specific types of objects will affect its versatility. Therefore, the container is made to only hold the object, that is, the reference of the root class of all objects, so that it can hold any type of objects. (Primitive is not included, because they are not objects and do not inherit other objects .) This is a great solution,:

1. Because the type information of an object is discarded when it is put into the container, the container has no limit on "What type of object can be added to the container. For example, even if you want it to hold only cat, others can easily put the dog in.

2. Because the object type information is lost, the container only knows the reference of the object it holds. Therefore, the object must be converted before use.
On the good side, Java won't let you misuse the objects in the container. Suppose you throw a dog to the cat container and use all the objects in the container as cat, when you pull the dog reference from the cat container and try to convert it to CAT, A runtimeexception is thrown.

The usage of arraylist is also very simple: first create an object, use add () to put the object in, and then pass a subscript to get () when using it-it's similar to using an array, we just don't need square brackets. Arraylist also has a size () method, which tells you how many objects are in the container, so that you do not carelessly pass through the bounds and then cause exceptions.

Sometimes it runs even if it is incorrect.
Sometimes, even if the object is not converted to the original type, it seems to work normally. There is a special case: the string can get some special help from where the compiler can work smoothly. As long as the compiler fails to get the expected String object, it will call tostring (). This method is an oily object definition that can be overwritten by any Java class. The string object returned by it will be used wherever it is used.

Therefore, you only need to overwrite the tostring () method of the class to print the object.

Create a type-sensitive arraylist

Parameterized types)

Iterator
No matter which container you use, you have to be able to store or take it out. After all, the main task of a container is to store objects. The add () of arraylist is used for putting objects in the East and West, while get () is used to take objects out. Arraylist is flexible. You can extract anything at any time and change the subscript to select another element immediately.

"Iterator is a design pattern" is an object, and its task is to make the customer program unknown, or, if you don't care about the underlying sequence structure that he processes, you can move the sequence before and after an object and select the object. In addition, the iterator is also a kind of "lightweight" object, which creates objects with low cost.

Java iterator is an iterator with such restrictions. It can't do many things:
1. Use the iterator () method to call the container to send you an iterator object. When you call the next () method of iterator for the first time, it will pass the first element in your sequence.
2. Use the next () method to obtain the next object in the sequence.
3. Use the hasnext () method to query whether there are other objects in the sequence.
4. Use the remove () method to delete the last element returned by the iterator.
That's all. This is just a simple implementation of the iterator, but it is still very powerful (for list, there is a more sophisticated listiterator ).

Casual recursion (unintended recursion)
Java's standard container classes (like other classes) inherit objects, so they also have a tostring () method. This method has been overwritten, so it can generate a string that represents itself and all the objects it stores. For example, the tostring () method of arraylist traverses every element of arraylist, and then calls their tostring () method. Suppose you want to print the Class address. It seems that the most direct method is to use this. However, many exceptions may occur. The solution is to call the tostring () method of the object, which is to do this. So do not use this. You should write super. tostring ().

Container Categorization
According to programming needs, collection and map have several implementations. In fact, there are only three container components-map, list, and set, and each has two to three implementations.
Interfaces related to object storage include collection, list, set, and map. Ideally, the vast majority of code should only deal with these interfaces, but the exact type of a container must be specified precisely when it is created.

Add (), as its name tells us, will put new elements into the collection. However, the document carefully states that "add () will ensure that the container contains the specified element ". This statement is for set, because it only adds elements that are not existing. For arraylist or other lists, add () always "put it in ", because list does not care whether it saves the same element.

Collection can use the iterator () method to generate an iterator. Here, we use iterator to traverse the entire collection and print them out.

Collection Functions
The following table lists all functions of collection, that is, what you can do with set and list (excluding Methods automatically inherited from objects ). (List also has some additional features .) Map does not inherit collection, so we will treat it differently.

Boolean add (object): Make sure that the container can hold the parameter you passed to it. If it is not added, false is returned. (This is an "optional" method. This chapter will explain it later .)
Boolean addall (Collection): Add all elements contained in the collection parameter. If an element is added, true is returned.
Void clear (): clears all elements saved by the container. ("Optional ")
Boolean contains (object): If the container holds the parameter object, true is returned.
Boolean containsall (Collection): returns true if the container holds all elements contained in the collection parameter.
Boolean isempty (): returns true if no elements are saved in the container.
Iterator (): returns an iterator that can be moved between elements of the container.
Boolean removeall (Collection): deletes all elements contained in the collection parameter in the container. Returns true if you have deleted the object. ("Optional ")
Boolean retainall (Collection): Only saves the elements included in the collection parameter (the concept of "intersection" in the set theory ). Returns true if any change occurs. ("Optional ")

Int size (): returns the number of elements contained in the container.
Object [] toarray (): returns an array containing all elements in the container.
Object [] toarray (object [] A): returns an array containing all elements in the container. This array is not a common object array, its type should be the same as that of parameter array A (type conversion is required ).

Note that there is no get () method for random access. This is because collection also includes set. Set has its own internal order (so it makes no sense to access it immediately ). So if you want to check the collection elements, you must use the iterator.

Next, let's talk about various implementations of list, set, and map. I will (use an asterisk) to tell you which implementation should be selected by default.

List Function
The basic usage of list is equivalent to. In most cases, you only use add () to add an object, get () to get the iterator of the sequence, and iterator () to obtain the sequence. However, there are other useful methods to list objects.

In fact, there are two types of list: Good At Random Access to elements, more commonly used arraylist, and more powerful sort list. The shortlist is not designed for fast random access, but it has a set of more common methods.

Lisk (Interface): The most important feature of list is order. It ensures that elements are saved in a certain order. List adds a large number of methods on the basis of collection, so that it can insert and delete elements in the middle of the sequence. (Recommended only for the shortlist .) A list can be used to create a listiterator object. In addition to inserting and deleting elements in the list, you can use it to traverse the list in two ways.

Arraylist *: A list implemented by arrays. Fast random access, but it is slow to insert or delete elements in the list. Listiterator can only be used for reverse traversal of arraylist. Do not use listiterator to insert or delete elements, because compared with the listiterator, listiterator has a high system overhead in arraylist.

Sequential list: sequential access is optimized. The cost of inserting and deleting elements in the list is not high. The random access speed is relatively slow. (Use arraylist .) In addition, it includes addfirst (), addlast (), getfirst (), getlast (), removefirst (), removelast (), and other methods (these methods, interfaces, and base classes are not defined ), you can use it as a stack, queue, or deque.

Remember, containers are just a box for storing objects. If this box can help you solve all the problems, you don't have to worry about how it works (in most cases, this is the basic concept of using objects ). If there are other factors in the development environment that may cause fixed performance overhead, the performance difference between arraylist and javaslist will become less important. You only need one of them. You can even imagine that there is such an abstract container that is "perfect". It can automatically switch its underlying implementation based on its purpose.

Use the consumer list to create a stack
"Stack" is also known as a "LIFO" container. That is to say, the last thing that is "pressed" into the stack will be first "popped up. Like other Java containers, the objects that are pressed in and popped out are all objects, so unless you only use the object function, you must convert the types of the items that are popped up.

The stacklist method can directly implement the stack function, so you can directly use the stacklist without writing the stack.
If you only want the stack function, inheritance is not suitable, because it inherits a class with all the methods of the listing list.

Use the queue list as a queue
A queue is a "first-in-first-out" (FIFO) container. That is, you put one end in and take it out from the other end. So the order in which you place the object is the order in which you take the object. The queue list can be used as a queue.

You can also easily create a deque (two-way Queue) using the queue list ). It is similar to a queue, but you can add or delete elements from any end.

Set Functions
The Set interface is collection, so unlike the two lists, it has no additional functions. In fact, set is actually a collection-it's just that the behavior is different. (This is the perfect use of inheritance and Polymorphism: express different behavior .) Set rejects instances that hold multiple objects with the same value (what determines the object's "value? This problem is complicated and will be discussed later ).

Set (Interface): Each element added to the set must be unique; otherwise, the set will not be added. To add set, the object must define equals () to indicate the uniqueness of the object. The Set interface is the same as the collection interface. The Set interface does not guarantee the order in which it stores elements.

Hashset *: set designed to optimize the query speed. The object to be put into the hashset must also define hashcode ().
Treeset: an ordered set with a tree at the bottom. In this way, you can extract an ordered sequence from the set.
Linkedhashset (JDK 1.4): a set that uses a linked list internally. It supports both the query speed of hashset and the order in which elements are added (insertion sequence ). When iterator is used to traverse a set, it accesses the set in the insert order.

The order in which hashset stores objects is different from that in treeset and javashashset. This is because they store and search for elements in different ways. (Treeset uses a data structure named Red-black tree data structure to sort elements, hashset uses the hash function "designed for fast search. Linkedhashset uses hashes internally to increase the query speed, but it looks like it uses a linked list to save the insertion sequence of elements .) When writing your own classes, you must remember that set must have a standard for determining the order in which elements are stored. That is to say, you must implement the comparable interface and define the compareto () method.

Sortedset
The elements in sortedset (only the treeset implementation is available) must be ordered. This adds some methods to the sortedset interface:
Comparator comparator (): returns the comparator object used by the Set lock, or uses null to indicate that it uses the object's own sorting method.
Object first (): returns the smallest element.
Object last (): returns the largest element.
Sortedset subset (fromelement, toelement): return the subset of the set, where the elements start from fromelement to toelement (including fromelement, excluding toelement ).

Sortedset headset (toelement): returns the subset of the set, where all elements should be smaller than toelement.
Sortedset headset (toelement): returns the subset of the set, where all elements must be greater than fromelement.
Note: sortedset indicates "sorting by object comparison order" rather than "insertion order.

Map Functions
Arraylist allows you to select numbers in the object sequence. In a sense, arraylist associates numbers with objects. However, if you want to select an Object Sequence Based on other conditions, what should you do? Stack is an example. The standard is "selecting the last object pushed into the stack ". Our commonly used terms map, Dictionary, or associative array are very powerful tools that can be selected in sequences. In terms of concept, it looks like an arraylist, but it does not need a number, but uses another object to find the object! This is a crucial programming technique.

This concept is represented by map in Java. The put (Object key, object Value) method adds a value to the map and associates the value with the key (the object you used for searching. After the key is given, get (Object key) returns the relevant value. You can also use containskey () and containsvalue () to test whether a map contains a key or value.

There are several map types in the java standard library: hashmap, treemap, linkedhashmap, weakhashmap, and identityhashmap. They all implement the basic interface of map, but they are obviously surprised at the behavior method. These differences are embodied in efficiency, holding and indicating the order of objects pair, length of time of holding objects, and how to determine the equality of keys.

In terms of performance, map faces a major problem. If you know how to work in get (), you will find (for example) Finding objects in arraylist is quite slow. This is the strength of hashmap. Instead of finding the key one by one, it uses a special value called hash code for searching. Hash is an algorithm that extracts some information from the target object and generates an int that represents the object. Hashcode () is the method of the object root class, so all Java objects can generate hash code. Hashmap uses the hashcode () of the object for quick search. In this way, the performance has been greatly improved.

Map (Interface): Maintain the key-value relationship (pairs), so that you can use the key to find the value.
Hashmap *: Based on the Implementation of hash tables. (Use it to replace hashtable .) Provides constant insertion and query time. You can set the capacity and load factor of the hash table in the constructor. You can adjust the performance of a constructor.

Linkedhashmap (JDK 1.4): similar to hashmap, but when iterator is used for traversal, it will be in the insertion order or the First Order (least-recently-used (LRU) Order). In addition to iterator, it is a little slower than hashmap in other cases. When iterator is used, because the chain table is used to save the internal order, the speed will be faster.

Treemap: based on the data structure of the red and black trees. When you view keys or pair, you will find them arranged in order (based on comparable or comparator, we will talk about it later. The treemap feature is an ordered map when you lock it. Treemap is the only implementation of submap () in map. This method allows you to obtain a part of this tree.

Weakhashmap: A map of Weak keys, designed for some special problems. It allows map to release its objects. If an object does not have its reference in other places except as a key in map, it will be treated as garbage collection.

Identityhashmap (JDK 1.4): A hash map that uses = instead of equals () to compare keys. It is not designed for our common use, but for solving special problems.

Hash is a common algorithm used to store data in map.

Sortedmap
Sortedmap (only the implementation of treemap) keys must be ordered, so there are some additional functions in this interface.
Comparator comparator (): returns the comparator used by map. If the built-in method of the object is used, null is returned.
Object firstkey (): returns the first key.
Object lastkey (): returns the last key.
Sortedmap submap (fromkey, Tokey): returns a subset of the map, whose keys start from fromkey to Tokey, including the former, not the latter.
Sortedmap headmap (Tokey): returns a choppy child set of the map, whose keys are smaller than the Tokey.
Sortedmap tailmap (fromkey): returns a subset of the map, whose keys are greater than or equal to fromkey.
Pair is stored in the order of keys. Because treemap has the concept of order, "location" makes sense. Therefore, you can obtain its first and last elements, and its subset.

Linkedhashmap
To increase the speed, linkedhashmap performs hash on everything, and during traversal (println () will traverse the entire map, so you can see this process) pair is also returned in the insert order. In addition, you can configure the linkedhashmap constructor to use the access-based LRU (least-recently-used) algorithm, in this way, elements that have not been accessed (and also candidate objects to be deleted) will appear at the beginning of the queue. In this way, it is easy to write a regular cleaning program to save resources.

Hash Algorithm and hash count
A proper equals () must be set to five points:
1 reverse: For any X, X. Equals (x), it must be true.
2 symmetry: For any X and Y, if y. Equals (X) is true, then
X. Equals (y) must also be true.
3 pass: For any X, Y, and Z, if X. Equals (Y) is true, and
Y. Equals (z) is true, so X. Equals (z) must also be true.
4 consistency: For any X and Y, if the object is used to determine that the information with the same surname is not repaired
After modification, no matter how many times X. Equals (Y) is called, it must return the same
True or false.
5. For any non-empty X, X. Equals (null) must return false.
The default object. Equals () simply compares the addresses of the two objects.
If you want to use the classes written in the subset as the hashmap key, you must overwrite the hashcode () and equals.

Understanding hashcode ()
If you do not override the hashcode () and equals () of keys, hash data structures (hashset, hashmap, linkedhashset, or linkedhashmap) cannot process keys correctly.

The value of hash lies in speed: the hash algorithm can quickly find something.
Array is the fastest data structure.

Hold reference
The Java. Lang. Ref class library has a set of classes that can improve the flexibility of the garbage collector. Once an object reaches the goal of consuming memory, these classes will be especially useful. There are three classes that inherit the abstract class reference: softreference, weakreference and phantomreference. If the objects to be processed can only be accessed through these references, these reference objects provide different levels of darkness to the garbage collector.

......

Summary:
1. An array associates objects with subscripts in numeric form. It holds objects of the specified type, so that you do not need to specify the type when extracting objects. It can be multidimensional or primitive. But its capacity cannot be changed after it is created.

2. Collection holds a single element, while map holds the associated pair.
3. Like arrays, list also associates numbers with objects. You can think of arrays and lists as ordered containers. The list automatically adjusts the capacity as the element increases. However, the list can only hold object reference, so it cannot store primitive. After the object is extracted, Type Transmission is required.

4. If you want to perform a lot of random access, use arraylist. However, if you want to perform a lot of insert and delete operations in the middle of the list, use explain list.
5. The queue list provides queue, two-way queue, and stack functions.
6. Map provides not the association of objects and arrays, but the association of objects and objects.
Hashmap focuses on access speed, while treemap focuses on key order, so it is not as fast as hashmap. Linkedhashmap maintains the order of object insertion, but it can also be re-ordered using the LRU algorithm.

7. Set only accepts non-repeated objects. Hashset provides the fastest query speed. Treeset maintains the order of elements. Linkedhashset maintains the insert sequence of elements.
8. There is no need to use the vectors, hashtable and stack left behind by the old class library in the new Code.
The container class library is a tool that you use every day. It makes programs more informative, powerful, and funny.

Related Article

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.