(Dark horse programmer-diary 2) Collection framework-every approaching, in exchange for only scars

Source: Internet
Author: User

------- Android training, Java training, and hope to communicate with you! ----------

During the past few days, I have reviewed my video on the Collection framework. Although I have a general concept for the class set in my head, I can't write anything when I want to use the set. I don't know where to use this item, and under what circumstances. The understanding of each type of set is not very deep. For example, how can I optimize the code by reading the hashcode () method and equals () method, you may find that your IQ is insufficient. Every time I got close to the Collection framework, all I had was scars.

To learn a new knowledge, follow the Convention and you must create a framework for this knowledge. I will first show the most common interfaces and collection subclasses in the set with a graph:

First, let's take a look at the concept. A set is an object used to store and manage other objects. It can be understood as an object container. It can also be resized, can be variable in length, and can store various types of data.

 

List Interface
The implementation of the List interface sub-class storage elements are ordered and can be repeated. Just like an array, each element has its own index. Its three main implementation subclasses have the following features:
1. The underlying layer of arraylist is an array structure. Features: Fast query, slow addition and deletion, and non-synchronization of threads
2. The underlying structure of the shortlist is a linked list. Features: Slow query and fast addition/Deletion
3. The bottom layer of the vector is an array structure, with Low thread synchronization efficiency. (No need to master)

 

ShortlistAddfirst, addlast, getfirst, getlast (get element, but do not delete element), removefirst, removelast (get element, but delete element, think of car in traffic light project, after crossing the road, the remove method is used. If there are no elements in the Set, the nosuchelementexception exception will occur. In jdk1.6, there is an alternative method: offerfirst, peeklast, pollfirst, if no element exists in the Set, null is returned ).

Here is a summaryData Structure of stacks and queues:
STACK: the first one is removed every time, just like a cup, removefirst, but this element is added at the end.
Queue: first-in-first-out, like a pipe, removelast. Each time the last one is removed, this element is added at the end.
 

Set Interface
Set: the elements are unordered (the order of storage and removal is not necessarily the same). elements cannot be repeated. Its functions are consistent with those of the collection interface.

Hashset: The underlying data structure is a hash table. If the hashcode method is rewritten, the same hash value will be extended after the hash value is saved to the hash set. If the hash value is the same, then compare whether the two elements are the same.

How does hashset ensure the uniqueness of elements?
The two methods of the element, hashcode and equals, are used. If the hashcode value of the element is the same, the system checks whether equals is true. If the hashcode value of an element is different, equals is not called. (when performing rewrite on the hashcode and equals methods, you must pay attention to the return value and parameter list. You cannot change the value at will, otherwise, it will not be re-written, but will be reloaded)

Note: For operations such as determining whether an element exists and deleting it, the dependent methods are the hashcode and equals methods of the element.

 

Treeset: Sorts the elements in the Set set.
The comparable interface forces the comparison of elements stored in the treeset set. This interface must be implemented and the comparato method in the rewrite is returned as Int. Many classes in JDK have implemented the comparable interface, such as string and integer. When sorting, if the primary condition is the same, it must be compared with the secondary condition. For example, if the stored element is a person, the age is compared before the name is compared.

 

The underlying layer of a treeset set is a binary tree. A small one is placed on the left and a large one on the right. For example, to traverse a set, the default sequence is from small to large. To ensure the uniqueness of elements, comparato returns 0.

 

The first way to sort a treeset set: to make the elements have a comparison, you must implement this interface and rewrite the comparato method in it. The return value is int. This method is also called the natural sequence of elements,

Default order.

The second method of treeset sorting: When the elements do not have a comparison, or the comparison is not required (for example, a student class has implemented the comparable interface, let yourself sort by age first, but what we need is to sort by name first), then we need to make the set itself have a comparison. When the set is initialized, a comparison method is available, that is, when a new set is introduced, a comparator is passed in. As follows:

Treeset Ts = new treeset (New mycomp ());

The mycomp class implements the comparator interface and describes the compare method. When both sorting methods are used, the comparator is used as the main component.

Remember: to create multiple objects and operate a class at the same time, you must implement the comparable interface and overwrite the hashcode and equals methods.

 

Generic

This is a new feature in jdk1.5 and later versions. It is used to solve security problems and is a security mechanism.
Benefits:
1. migrate the classcastexception that occurs during the runtime to the compilation period to help solve the problem with the programmer and reduce the problem during the runtime.
2. This avoids the trouble of forced conversion.

 

Static methods cannot be generic defined on the generic class. If the data type of the application operated by the static method is uncertain, the generic type can be defined on the method.

For example:

Class test <t>

{

Public static <E> void method (){...}

}

Note: generics can only be written before the return value type.

 

<T>, <?> The difference between the two: T represents the specific type. What type are you passing in ,? It indicates a placeholder. Here there is a generic type. It is not clear which type is specific. <?> You cannot use a special method of the type.

? Extends E: it can accept the subtype of E or E. The upper limit is
? Super E: can accept the parent type of E or E, the lower limit

Map Interface:

The map interface has several major implementation subclasses:
1. hashtable: The underlying layer is the data structure of the hash table. It cannot be saved to null values of the null key. thread security is generally not used.
2. hashmap: The underlying layer is the data structure of the hash table. null values can be used. This set is not synchronized.
3. treemap: The underlying layer is a binary tree and threads are not synchronized. It can be used to sort keys in the map set.

The map interface is similar to the set interface. At the underlying layer of the Set interface, the map set is used. A map type set stores a ing relationship.

The put method returns the original value corresponding to the key. The key must be unique. If the key is the same, the added value overwrites the original value.

 

There are two methods to retrieve a map set:
1. keyset: store all the keys in the map to the Set set, because the set has an iterator. All the keys that can be retrieved through iteration, and then obtain the value of each key based on the get method.

2. Set <map. entry <K, V> entryset: stores the ing relationships in the map set into the set, and the Data Type of the ing is map. after obtaining the Link View, use map. the getkey and getvalue methods in the entry get the key and value.

 

The entry interface is an internal interface of the map interface and is defined as follows:
Interface Map
{
Public static interface entry
{
Public abstract object getkey ();
Public abstract object getvalue ();
}
}

 

Why define the entry in map? Because the entry stores the ing relationship of key-value pairs (this relationship is considered as a type), only with map will there be a key-value ing relationship.

 

Two tool classes: collections and Arrays
Collections
Classes used specifically for set operations are static methods. (Mainly for List Set Operations)
1. The sort () method can sort list sets to make up for the lack of comparator.
2. the max () method returns the maximum value in the list set, that is, the last value after sorting in order.
3. binarysearch () performs binary search on the elements in the list.
4. Fill () replaces all elements in the set with an element.
5. replaceall () replaces an element.
6. Reverse () reverses the elements in the set.
7. reverseorder () Forcibly reverses the comparator and returns a comparator.
8. Swap () Replacement
9. Shuffle () sorts the elements in the Set in a random manner.

 

ArraysThe tool class used to operate the array, which is also a static method.
Aslist () returns an array that supports the list and converts the array into a list set (What are the benefits of converting the array into a set? You can use the idea and method of the set to operate the elements in the array)

Note: changing an array to a set does not allow the addition or deletion of a set, because the length of the array is fixed (but the modification and query operations are allowed, such as get, contains, indexof, sublist can be used ).

If the elements in the array are all objects, the elements in the array are directly converted into elements in the set when the elements are converted into a set.
If the element in the array is of the basic data type, the array will exist as the element in the set when it is converted to a set.

As follows:
Example 1: int [] Nums = {1, 2, 3 };
List <int []> List = arrays. aslist (Nums );

Example 2: String [] STR = {"AA", "BD", "Ni "};
List <string> List = arrays. aslist (STR );

 

Array of set changes:
Use the toarray method in the collection Interface
1. How long does an array of the specified type need to be defined?
When the length of an array of the specified type is smaller than the size of the set, a new array is created in this method, and the length is the size of the set.
When the length of an array of the specified type is greater than the size of the set, the array is not created, but the passed array is used. Therefore, the optimal array is created.

Arraylist <string> Al = new arraylist <string> ();
String [] arr = Al. toarray (New String [Al. Size ()]);

 

2. Why should we change the set to an array?
To limit the operation on elements, you do not need to add or delete the set.

Set Traversal method:

1. Traditional For Loop
2. Advanced for loop, for (Object OBJ: List)
3. traverse through the iterator to understand the differences between iterator and listiterator. One is the son and the other is Lao Tzu, And the other son must have methods that Lao Tzu does not have, therefore, listiterator can add or delete objects during traversal, but iterator cannot.

 

Finally, let's make a comprehensive summary:

1. treeset is used for sorting. Because the treeset storage efficiency is low and the hashset storage efficiency is high, you can put the elements in the hashset into the treeset when you need to sort the hashset object.

2. In map, if you often need to insert, delete, and locate elements, it is best to use hashmap. If you often traverse keys in order, treemap is an ideal choice.

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.