Java Containers (2)

Source: Internet
Author: User

P474) arrays.aslist () generates a list that is based on a fixed-size array that supports only those operations that do not change the size of the array. Any method that causes the size of the underlying data structure to be modified will result in a Unsupportedoperationexception exception that represents a call to an unsupported operation.

The result of arrays.aslist () should be passed as a constructor parameter to any collection (either using the AddAll () method, or the static method of Collection.addall (), which generates a generic container that allows all methods to be used. The "Non-modifiable" method in the Collections class wraps the container into a proxy, which generates an unsupportedoperationexception exception whenever you perform any action that attempts to modify the container.

The difference between iterator and Listiterator

P477)Set

Set (interface) Set does not save duplicate elements, the element that joins set must define the Equals () method to ensure the uniqueness of the object. Set and collection have exactly the same interface. The set interface does not guarantee the order in which elements are maintained.
HashSet Find the speed block. The deposit element must define HASHCODE ().
TreeSet The set of the hold order, the bottom is the tree structure. Use it to extract ordered sequences from the set. The element must implement the comparable interface.
Linkedhashlist has hashset query speed, and internally maintains the order of elements (in order of insertion) with the linked list. Element must also define the Hashcode () method.

P479) When comparing the size of two integer values in CompareTo (), do not use (I1-I2) as the return value (unless there is unsigned int, but Java does not), because a large positive number minus a large negative may overflow causing a large negative amount to be returned (honestly <, > and = =).

P485)Map

HashMap Map is based on the implementation of the hash table (it replaces the Hashtable). The cost of inserting and querying "key-value pairs" is fixed. You can set capacity and load factors through the constructor. To adjust the performance of the container.
Linkedhashmap Similar to HashMap, but when iterating through it, the order in which to get "key-value pairs" is its insertion order, or the least recently used (LRU) order. It is only a bit slower than the hashmap, while the iterative access is faster because it uses the list to maintain the internal order.
TreeMap Based on the implementation of red-black trees. When viewing "key" or "key-value pairs", they are sorted (in order by comparable or comparator). TreeMap is characterized by the fact that the resulting structure is sorted. TreeMap is the only map with the Submap () method, which can return a subtree.

P489) hash and hash codes

The Hashcode () method of the object generates the hash code by default, using the object's address to calculate the hash code. At the same time, Object.Equals () is simply the address of the comparison object. Therefore, if you want to use your own class as the HashMap key, you must overload both Hashcode () and Equals ().

P496) cover hashcode ()

to Hashcode () practical, it must be speed blocks, and must have meaning. That is, it must generate a hash code based on the content of the object (more attention should be paid to build speed than uniqueness). However, by Hashcode () and Equals (), you must be able to fully determine the identity of the object. In addition, a good hashcode () should produce a distributed hash code. Here are the basic instructions for writing a decent hashcode ():

1) give an int variable result to a non-0-value constant

2) computes an int hash code c for each meaningful field F in the object:

Boolean c = (f? 0:1)
Byte, char, short, or int c = (int) f
Long c = (int) (f ^ (f >>> 32))
Float c = Float.floattointbit (f);
Double

Long L = double.doubletolongbits (f);

c = (int) (i ^ (i >>> 32))

Object whose equals () call Equals () of this domain c = F.hashcode ()
Array Apply the above rules to each element

3) combined computed hash code: result = 37xresult + C;

4) return result.

5) Check the results of the last generation of hashcode () to ensure that the same hash code is available for the same object.

P499) Select different implementations of the interface

The ArrayList is supported by arrays, whereas LinkedList is implemented by a doubly linked list, where each object contains data and also contains a reference to the previous and subsequent element in the linked list. Therefore, if you want to frequently insert or delete elements in a table, LinkedList is more appropriate (LinkedList also have other features built on abstractsequentiallist); otherwise, you should use a faster ArrayList.

P507) The range of Math.random () is [0,1];

P512)static methods inside the collections class

Rotate (List, int distance): All elements move backward distance positions, looping the elements at the end to the front.

Swap (list, int i, int j): Swaps the elements of position I and position J in the list. Usually than you write your own block.

P515) set collection or map as non-modifiable

Collections.unmodifiablecollection (Collection);

Collections.unmodifiablelist (List);

Collections.unmodifiableset (Set);

Collections.unmodifiablesortedset (Set);

Collections.unmodifiablesortedmap (MAP);

Either way, you must fill in meaningful data before you set the container to read-only.

P517) Quick Error

The Java container has a protection mechanism that prevents multiple processes from modifying the contents of the same container at the same time. If you iterate through a container and another process intervenes, and you insert, delete, or modify an object within the container, the problem occurs.

The Java Container Class library uses the quick error mechanism. It will probe for any changes in the container other than what your process is doing, and once it discovers that other processes have modified the container, it will immediately throw a concurrentmodificationexception exception.

Concurrentmap, Copyonwritearraylist, and copyonwritearrayset all use techniques that can avoid concurrentmodificationerror.

P518) hold references

The Java.lang.ref class library contains a set of classes that provide greater flexibility for garbage collection. These classes are especially useful when there are large objects that can run out of memory. There are three classes that inherit from the abstract class reference: SoftReference, WeakReference, and Phantomreference.

If you want to continue to hold a reference to an object and want to be able to access the object later, but also want to allow the garbage collector to release it, you should use the Reference object. With the reference object as the medium between you and the ordinary reference (proxy), in addition, must not have ordinary references to that object, so that can achieve the above purpose.

SoftReference, WeakReference, phantomreference are arranged from strong to weak, corresponding to different levels of "availability".

When using SoftReference and WeakReference, you can choose whether you want to put them in referencequeue (as a tool for "clean up before recycling"). And phantomreference can only rely on referencequeue.

The specific usage of these three reference and Weakhashmap.

Java Containers (2)

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.