[Think In Java] basic collection 3, think collection
Directory
Chapter 4 objects held
Chapter 2 deep research on Containers
Chapter 2 Java I/O system
Chapter 4 objects held
1. java container Overview
Two main types of java containers (the main difference between them is the number of elements saved in each "slot" in the container): Collection and Map.
(1) Collection is a sequence of independent elements, all of which follow one or more rules. Collection summarizesSequenceConcept-a way to store a group of objects.
- List: Save elements (ArrayList, sort List) in the inserted order)
- Set: duplicate elements (HashSet, TreeSet, and repeated hasset) are not allowed)
- Queue: followQueuing rulesTo determine the order in which objects are generated (by queue time, that is, FIFO, by priority)
(2) Map is a "key-Value Pair" Object consisting of a pair. You can use a key to find the value.
- HashMap: unordered
- TreeMap: stores keys in ascending order of comparison results.
- LinkedHashMap: stores keys in the insert sequence.
2. Related tool classes: java. util. Arrays and java. util. Collections.
(1) Add a group of elements
Arrays. asList ();
Collections. asList ();
(2) Container Printing
Arrays. toString ();
3. iterator
Traverse the container, regardless of the specific type of the container. The iterator is also a design pattern. (Similar to the iterator in C ++)
The Collection interface has an iterator () method to return an Iterator object, that is, each container that inherits from the Collection can be iterated (the Collection interface inherits from the Iterable interface ). Iterator has the following methods:
Boolean hasNext (): returns true if there are still elements that can be iterated.
E next (): returns the next element of the iteration.
Void remove (): removes the last element returned by the iterator from the collection to which the iterator points (optional, not all containers implement this method ).
4. ListIterator
ListIterator inherits from Iterator. Iterator can only move forward, but ListIterator can move two-way. ListIterator can only be used for various lists.
5. Set
It is not feasible to put two identical objects into the Set. Set is object-basedValueTo determine the attributes.
HashSet: Based on the hash function; TreeSet: Based on the red/black tree; LinkedHashSet: hash Function + linked list.
TreeSet uses the natural sequence of elements to sort the elements, or sorts the elements based on the Comparator provided when the set is created, depending on the construction method used.
The String class has a comparator String. CASE_INSENSITIVE_ORDER;
6. PriorityQueue
An unbounded priority queue based on the priority heap. The elements of the priority queue are sorted in the natural order, or by the Comparator provided when the queue is constructed, depending on the construction method used.
7. Simple container classification
Chapter 2 deep research on Containers
1. Complete container classification
Shows a complete diagram of the Java container class library, including abstract classes and legacy components (excluding the implementation of Queue ).
Commonly used containers are represented by a black rough box, a dotted box represents an interface, a dotted box represents an abstract class, a solid box represents a class, and a hollow arrow represents an implementation relationship. Produce indicates that any Map object can generate Collection objects, and any Collection object can generate Iterator objects.
2. Container Summary
The following table summarizes the features of the List, Set, and Map interfaces and their implementation classes:
|
Features |
Implementation class |
Implementation features |
Requirements for elements to be placed |
List |
A linear and ordered storage container that can access the get (n) element through an index) |
ArrayList |
Array Implementation. Non-synchronous. |
|
Vector |
Synchronization is similar to ArrayList. |
|
Shortlist |
Two-way linked list. Non-synchronous. |
|
Set |
The element cannot be repeated. The element must define the equals () method. |
HashSet |
Set for quick search |
The element must define hashCode () |
TreeSet |
Set in order. The underlying layer is the tree structure. |
The element must implement the Comparable Interface |
LinkedHashSet |
Use a linked list internally to maintain the sequence of elements (insertion order) |
The element must define hashCode () |
Map |
Saves key-Value Pair members. All keys in Map must define the equals () method. |
HashMap |
Implementation of Map interface based on hash table to meet General requirements |
The key must have an appropriate hashCode (). If you modify the equals method, you must modify the hashCode method at the same time. |
TreeMap |
Sort by default in the natural order, or sort by the Comparator provided when the ing is created. |
The key member must implement the caparable interface, or use Comparator to construct a TreeMap. Key members are generally of the same type. |
LinkedHashMap |
Similar to HashMap, the order in which key-value pairs are obtained through iteration is the insertion sequence or the least recently used sequence. |
Same as HashMap |
IdentityHashMap |
Use = to replace equals () to compare the hash ing of "key value" |
The member uses = to determine whether the Member is equal. |
WeakHashMap |
Weak key ing, allowing you to release the objects pointed to by the ing |
|
ConcurrentHashMap |
Thread-safe Map |
|
Note:
(1) Various Queue and Stack behaviors can be fully supported by the Queue list. The preceding table does not contain Queue.
(2) However, all hash-related operations will inevitably design the hashCode method, because the location of the object in the hash table should be calculated based on the returned hash code. However, for any Tree-related operations, the Comparable interface must be designed because sorting is involved.
(3) If you want to perform a large number of random access, you can use ArrayList. If you want to insert or delete elements from the middle of the table frequently, you should use explain list. During traversal, The get method is preferred for the ArrayList, And the iterator method is preferred for the worker list.
(4) Collection inherits the Iterable interface, so all Collection objects can use the foreach method to traverse elements. All Collection objects are hiuforeach loops that can work with any object that implements the Iterable interface.
(5) When a custom class is used as the key of HashMap/HashSet/LinkedHashMap/LinkedHashSet, The equals () and hashcode () methods must be overwritten at the same time.
3. Write the hashcode () method
4. Performance Factor of HashMap
Several terms:
(1) Capacity: number of bits in the table
(2) initial capacity: Number of BITs owned by the table during creation. You can specify the initial capacity in the constructor of HashMap and HashSet.
(3) size: the number of items currently stored in the table.
(4) load factor: Size/capacity.
Both HashMap and HashSet have constructors that can specify the load factor, indicating that when the load condition reaches the load factor level, the container will automatically increase its capacity (number of BITs ), the implementation method is to roughly double the capacity and re-distribute existing objects to the new bucket set (and then hash ).
The default load factor used by HashMap is 0.75.
5. fast Error (fail-fast)
Java containers have a protection mechanism to prevent multiple processes from simultaneously modifying the content of the same container. The Java container class library uses the fail-fast mechanism to detect all the changes on the container except the operations performed by your process, once it finds that other processes have modified the container, it will immediately throw a ConcurrentModificationException. This is the meaning of "quick Error Reporting"-that is, it is not to use complicated algorithms to check problems afterwards.
ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteArraySet both use techniques that can avoid ConcurrentModificationException.
6. Hold reference
If you want to continue to hold a Reference of an object and want to access it later, but want to allow GC to release it, you should use the Reference object. In this way, you can continue to use this object, and allow the object to be released when the memory is exhausted.
The Reference object is used as a medium (proxy) between you and a common Reference. In addition, there must be no normal Reference pointing to that object, so that the above purpose can be achieved. (Normal Reference refers to a Reference that has not been encapsulated by the Reference object .) If GC finds that an object is available through normal reference, the object will not be released.
[This is similar to shared_ptr in C ++, and it is also similar to RAAI when creating a Reference object.]
A a = new A (); // objects referenced by a (common Reference) cannot be recycled. Reference B = new Reference (new ()); // The object of application B can be recycled because the object (often a large object) is wrapped at birth and can be recycled without other common references pointing to it.
SoftReference, WeakReference, and PhantomReference are strongly or weakly arranged, corresponding to different levels of "availability ".
Chapter 2 Java I/O system
1. InputStream
This abstract class is a super class that represents all classes of the byte input stream.
[In combination with the FILE stream pointer struct FILE in the C language in linux, you can understand it. In Linux, All I/O devices are files, so such a struct represents various data sources in the system, but in Java, specific data sources are represented by subclasses of InputStream, for example, AudioInputStream, ByteArrayInputStream, FileInputStream, PipedInputStream, SequenceInputStream, and StringBufferInputStream.]
The specific table is as follows:
2. OutputStream
Similar to InputStream. The following table
3. IO class and decorator mode in Java
The Java I/O class library is designed in the decorator mode.
First, let's look at the UML diagram of the decorator mode: (For details, refer to Wikipedia)
UML diagram corresponding to java IO
FilterInputStream and FilterOutputStream play the role of the abstract modifier. Their subclass is the specific modifier.
See the following table:
4. Reader and Writer
Unlike InputStream and OutputStream for byte IO, Reader and Writer provide Unicode and character IO-oriented functions.
The inheritance hierarchies of Reader and Writer are designed to be internationalized. Because InputStream and OutputStream only support eight-byte streams, they cannot properly process 16-bit Unicode characters.
5. Adapter class in IO
(1) InputStreamReader: byte --> character (2 bytes)
InputStreamReader is a bridge between byte stream and byte stream:It reads bytes using the specified charset and decodes them into characters.. Its character set can be specified by name or explicitly specified, or it can accept the default Character Set of the platform.
Each time you call a read () method in InputStreamReader, the input streamReads one or more bytes..
To achieve the highest efficiency, InputStreamReader should be packaged in BufferedReader. Example: BufferedReader in = new BufferedReader (new InputStreamReader (System. in ));
(2) OutputStreamWriter: character (2 bytes) --> byte
OutputStreamWriter is a bridge between the bytes stream and the byte stream: You can use the specified charset to write data toCharacter encoding into bytes. The character set used by the platform can be specified or explicitly specified by the name. Otherwise, the default Character Set of the platform will be accepted.
[Correct memory mistakes]: Previously, OutputStreamWriter was recorded to encode bytes into characters. This can be used to correct the memory:
(1) From the OutputStreamWriter constructor:
OutputStreamWriter requires an OutputStream object. Therefore, the form indicates that the byte stream is converted to the bytes stream. In fact, this is not the case. The constructor requires OutputStream only because OutputStreamWriter needs to use OutputStream to complete specific output operations.
(2) From the perspective of the function call relationship: OutputStreamWriter. writer (character char) --> OutputStream. write (byte)
After calling OutputStreamWriter, we get a Writer, and the Writer's write () method parameters are all characters. It can be imagined that the characters written by calling the write () function of OutputStreamWriter must be converted to the internal OutputStream object for throttling. Therefore, this OutputStreamWriter class actually encodes characters into bytes.
6. Standard IO redirection in Java
The static methods of the System class are as follows: setErr (), setOut (), and setIn () can redirect IO. All the parameters of these functions are callback streams.
7. Process Control
Java involves two types of Process control: Process and ProcessBuilder. The latter is used to create an operating system process and returns an instance of the former.
8. Java NIO
The idea is similar to IO reuse in Linux. For details, refer to introduction to NIO.
9. Object serialization
(1) concept: java object serialization is to convert the objects that implement the Serializable interface into a byte sequence and completely restore the byte sequence to the original object in the future.
(2) Why object serialization?
The concept of object serialization is added to the language to support two main features. First, Java RMI. When sending messages to a remote object, parameters and returned values must be passed through object serialization. Second, Object serialization is required for JavaBean. You need to save its status information during the design phase, and restore it after the program starts.
(3) specific steps: Let the class to be serialized implement a mark interface Serializable, then the object of this class is Serializable.
Refer to this blog