[Java learning notes] Collection class

Source: Internet
Author: User
Tags set set

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. Collection features:

They are all located in the Java. util package. They cannot store basic types of data, but can only store object references. The number of operations can be unfixed (similar to dynamic arrays ).

 

2. Category:

There are three types:

A. Set: objects are not sorted in a specific way,No repeated Elements. This is most similar to the Set Concept in mathematics.

B. List: sort by index location,There can be repeated ElementsAllows you to retrieve Objects Based on their index locations in the set.

C. MAP: Each element contains a key-value pair. There are no duplicate key-value pairs, but the value objects can be repeated.

 

There are two interfaces:

The collection interface is applicable to set and list in a Java set (these two classes directly inherit this interface) and provides some static methods for general operation.

The iterator interface hides the data structure of the underlying set and provides a unified interface for Traversing various data types sets. An iterator is obtained from the iterator of the collection. Syntax:

Iterator it = set. iterator ();

(Note that if the set is modified using the collection method, an exception will occur when the next () method is used, because it uses the so-called fast failure mechanism. Avoid concurrency problems caused by potential competition for shared resources ).

3. Set set:

There are two main implementation classes: hashset and treeset.

The former uses a hash algorithm to accelerate access. It also has a subclass of javashashset class with higher performance. When a hashset adds an object to the set, it calls the hashcode () method of the object to obtain the hash code, and then calculates the storage location of the object in the Set Based on the hash code.

To ensure normal operation, the two objects must have the same hash code when they are compared with true using the equals () method. This requires that if we overwrite the equals method in the class we designed, we should also overwrite the hashcode () method. When the comparison result of equals () is false, it is better to have different hashcodes to reduce hash conflicts and improve performance.

The latter implements the sortedset interface and has the sorting function. The user attribute changes will not cause re-sorting, so it is suitable for adding immutable classes. When adding a custom class to it, pay attention to implementing its comparable interface, and euqals () should come to the same conclusion as compareto. In addition, it also supports the comparator interface. You can define a class customercomparator that implements this interface to implement custom sorting. Use the following syntax for definition:

Set set = new treeset (New customercomparator );

 

4. List list:

The main feature is linear storage, and repeated elements can be stored in the set. A consultant at thoughts works has prepared that it is strongly recommended to use list in Java to replace all arrays. Use the aslist method when converting arrays and lists.

There are two main implementation classes: arraylist and rule list.

The former feature allows fast Random Access to elements, but it is slow to insert or delete elements. It is generally used to represent a variable array.

The latter adopts the Linked List data structure to quickly access, delete, and insert elements in sequence, but the random access speed is slow. Generally used to represent stacks, queues, and two-way queues.

A more practical interface is the listiterator interface, which is returned using the listiterator method. It inherits the iterator interface and provides a method to manipulate the list.

An aslist () method of the arrays class can wrap an array into a list object, but this list has a fixed length, because all operations will apply to the underlying array.

In the past, there was another Vector class, which is no longer recommended.

In terms of performance, the random access and iteration operations of Java arrays are the fastest, and the random access speed of arraylist is also faster, while the random list operation is the fastest.

Therefore, try not to perform iterative operations in the list.addAllOrremoveAllTo transfer the content of a set (especially a set converted from an array) to another set, you can also remove a small object set from a large object set to add or remove members. Iterations may encounter the following problems:

  • It is inefficient to re-adjust the set after each element is added or removed.
  • Each time the lock is acquired, the operation is executed, and the lock is released, there is a potential concurrency dilemma.
  • When an element is added or removed, other threads that access the collection may compete.
  •  

     

    5. Map ing:

    Each element contains a key-value pair, and the value object can also be mapped to the map type. duplicate key objects are not allowed.

    The entryset () method of map returns a set, which stores elements of the map. Entry type. Each map. Entry object represents a key-Value Pair in map. The keyset () method returns the set of all key objects in the set.

    There are two main implementation classes: hashmap and treemap, which have the same features and usage instructions as set.

    Note: never use a mutable object typeHashMapOtherwise, the key supporting the hash code depends on the content of the variable field.hashCode()It is easy to change and generate bugs.

     

    6. Precautions for use:

    1) In generics, a set-like expression can be used to only accept the object type and its subtypes. Or set indicates that the string type and its parent type are accepted.

    2) You can use a simpler Traversal method to replace iterator. This enhancement is suitable for implementation.IterableInterfaceAny object, Not justCollections:

    For (string element: Set ){

    System. Out. println (element );

    }

    3) the set, list, and map implementation classes do not adopt a synchronization mechanism. Pay attention to concurrency issues.

    4) collections class, which can be called directly (because it is static) by using collections. Sort (list). Be sure to distinguish it from the collection interface.

    5) when a Member is removed from a list, the items next to it will rise to fill the gap, which may be significantly different from the array.

     

    Author: gnuhpc
    Source: http://www.cnblogs.com/gnuhpc/

    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.