A collection of
The Java collection class is defined in the java.util package. There are four types of collections: List, Queue, Set, and Map.
The List can be repeated
List is a very common data type. It is an ordered Collection and its three implementation classes are ArrayList, LinkedList, and Vector.
- ArrayList: An array-based List that is slow to add and delete, fast to query, and unsafe to thread
- Vector: Implemented based on arrays, it is slow to add and delete, fast to query, and thread safe
- LinkedList: based on double LinkedList implementation, fast add and delete, slow query, thread safety
Queue
- ArrayBlockingQueue: Array-based implementation of a bounded blocking queue
- LinkedBlockingQueue: a bounded blocking queue based on a linked list implementation
- PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting
- DelayQueue: an unbounded blocking queue that supports delayed operations
- SynchronousQueue: The blocking queue used for thread synchronization
- LinkedTransferQueue: An unbounded blocking queue based on a linked list implementation
- LinkedBlockingDeque: Bidirectional blocking queue implemented based on a linked list structure
Set is not repeatable
- HashSet: Implementation of HashTable, unordered
- Comparable: Binary tree implementation, ordered, custom data types must implement the Comparable interface and override the compareTo method in it, returning -1 in ascending order and 1 in descending order
- LinkHashSet: HashTable implements data storage, bidirectional linked list records the order
Map
HashMap: Array + linked list stores data, not thread safe.
If thread-safe conditions need to be met, the Collections synchronizedMap method can be used to make HashMap thread-safe, or ConcurrentHashMap can be used.
The data structure of a HashMap: Inside is an array in which each element is an instance of Entry and contains four attributes: key, value, hash, and next to point to the next element in the one-way list.
Common parameters:
- Capacity: Indicates the capacity of the current array. The default value is 16. It can be expanded twice
- LoadFactor: loadFactor. The default value is 0.75
- Threshold: indicates the capacity expansion threshold. The value is capacity x loadFactor
When a HashMap queries data, it can directly find the index of the array where the data resides based on the hash value. However, it takes O (n) time to traverse the entire linked list under the array to query data.
To reduce list traversal time, Java8 optimizes HashMap by changing the data structure to either data + list or array + red-black tree. After the list has more than eight elements, HashMap converts the list structure into a red-black tree structure to improve query efficiency.
ConcurrentHashMap: segmented lock implementation, thread-safe
The concurrencyLevel parameter indicates the parallelism level. The default value is 16, in which a maximum of 16 threads can concurrently execute writes. This value can be set during initialization and cannot be changed after initialization.
HashTable: Thread safety
Thread-safe, but only one thread can perform writes at a time, which is less concurrency than ConcurrentHashMap.
TreeMap: Implemented based on binary tree
When using a TreeMap, its key must implement the Comparable interface or using custom comparator, otherwise it will throw the Java. Lang. ClassCastException.
LinkedListHashMap: Use a linked list to hold the insertion order
Anomaly classification and handling
In Java, Throwable is the parent class of all errors or exceptions, and Throwable can be divided into Error and Exception.
Error refers to the Java operation Error. If the program is started with Error, the startup fails. If the program is run with Error, the process exits safely. Error is usually caused by internal system errors or resource exhaustion. The system cannot process errors dynamically at runtime. What it can do is to record the cause of errors and exit safely.
An Exception is a Java runtime Exception. An unexpected event occurs during the execution of a program and can be handled by the Java Exception handling mechanism. Exception is divided into RuntimeException (RuntimeException) and CheckedException (check Exception)
- RuntimeException: An exception thrown during normal running of the Java virtual machine. RuntimeException can be captured and handled
- CheckedException: At compile time the Java compiler checks for CheckedException exceptions and forces them to be captured and handled, such as IOException, SQLException, ClassNotFoundException, etc
Reflection mechanism
Reflection mechanism is that in the process of program running, any class can get all its attributes and methods, and any object can call any method. This ability to dynamically retrieve information about classes and objects, as well as dynamically invoke methods on objects, is called Java’s reflection mechanism.
There are two types of objects in Java: compile-time and run-time. Compile-time types are the types used when declaring objects, and run-time types are the types used when assigning values to objects.
Java’s reflection API
- Class: Used to get information about Class attributes, methods, etc
- Field class: Represents the member variables of the class that are used to get and set the values of attributes in the class
- Mathod class: A method that represents a class and is used to obtain description information about a method or to execute a method
- Constructor class: represents the Constructor of a class
Steps of reflection
- Gets the Class object of the Class you want to operate on, which is the core of reflection
- Call the method defined in the corresponding Class object, which is the use phase of reflection
- Use the reflection API to retrieve and invoke information such as properties and methods of a class
There are three ways to get a Class object:
Person p = new Person(); Class clazz = p.getClass(); Class clazz = person.class (); Class clazz = class.forname ("fullClassPath"); // Call the static forName method of the Class Class, which is the safest and highest performance method. / / the name of the classCopy the code
Once you have the Class object of your Class, you can get and view the methods and properties of the Class through the methods in the Class
Class clazz = class.forname ("fullClassPath"); [] methods = clazz.getDeclaredMethods(); Field[] fields = clazz.getDeclaredFields(); / / for all Person class Constructor information Constructor [] constructors = clazz. GetDeclaredConstructors ();Copy the code
Two ways to create an object
// Use the Class object's newInstance method, which requires the Constructor to take empty arguments to the corresponding Class. Class clazz = class.forname ("fullClassPath"); Constructor c = clazz.getDeclaredConstructor(String.class, String.class); Person p = (Person) c.newinstance (" sledge ", "male ");Copy the code
Method’s invoke Method
Class clz = Class.forName("fullClassPath");
Method method = clz.getMethod("setName", String.class);
Constructor constructor = clz.getConstructor();
Object object = constructor.newInstance();
method.invoke(object, "dachui");
Copy the code
annotations
The concept of annotations
Annotations are a method provided by Java to set the association information and metadata of elements in a program. It is an interface that allows a program to obtain metadata information in annotations by reflecting an Annotation object of elements in a specified program.
Standard meta-note
Meta-annotations are responsible for annotating other annotations.
@target // defines the scope of the object that the annotation modifies. @retention // defines the level at which the annotation is retained. Documented // Indicates that the annotation should be Documented by the Javadoc tool. @inherited // Indicates that an annotated type is InheritedCopy the code
Annotation processor
Define the annotation interface
@Traget(elementType.field) @Retention(RetentionPolicy.runtime) @Documented Public @Interface FruitProvider {// Vendor number public int id() default -1; Public String name() default ""; Public String address() default ""; }Copy the code
Using the Annotation interface
@fruoitProvider (id = 1, name = "FruoitProvider ", Address =" Xi 'an ") private String appleProvider; // setter()... // getter()... }Copy the code
Defining annotation handlers
public class FruitInfoUtil { public static void getFruitInfo(Class<? > clazz) { Field[] fields = clazz.getDeclaredFields(); for(Field field : fields) { if(field.isAnnotaionPresent(FruitProvider.class)) { FruitProvider fruitProvider = (FruitProvider) field.getAnnotion(FruitProvider.class); System.out.println(" + fruitprovider.id () + ") " + fruitProvider.address()) } } } public static void main(String[] args) { FruitInfoUtil.getFruitInfo(Apple.class); }}Copy the code
Inner classes (Programming thought supplement)
Classes defined inside a class are called inner classes. Depending on the method defined, they can be divided into static inner classes, member inner classes, static inner classes, and anonymous inner classes.
Static inner class
A static inner class can access static variables and methods of an external class. Static inner classes allow you to define static variables, methods, constructors, and so on.
The Java collection class HashMap internally maintains a static Node array of inner classes to hold elements while Node data is transparent to the consumer. Classes like this, which are closely related to external classes and do not depend on instances of external classes, can be implemented using static inner classes.
Member inner class
Member inner classes do not define static methods and variables (except for final modifications).
Local inner class
Classes defined in a method are called local inner classes, which can be elegantly implemented when a class needs to be used only in a method.
Anonymous inner class
A class defined and used by inheriting a parent class or implementing an interface
The generic
The nature of generics is parameterized types.
Without generics, we can use the reference Object class to implement arbitrary parameterization.
The benefit of using generics is that you can check type safety at compile time, and all mandatory type conversions are automated and implicit, improving code security and reuse.
Generic markup and generic qualification: E, T, K, V, N,?
The serial number | The generic tag | instructions |
---|---|---|
1 | E-Element | Used in a collection to represent the elements stored in the collection |
2 | T-Type | Said Java classes |
3 | K-Key | Said key |
4 | V-Value | Said value |
5 | N-Number | Presentation data type |
6 | ? | Represents an indeterminate Java type |
Type erasure
Type parameters added to generics during coding are removed by the compiler at compile time, a process called type erasure.
First, find the concrete class (typically Object) to replace type parameters, use an upper bound on type parameters if defined, and then replace all type parameters in your code with concrete classes.
Serialization (Principle to be added)
To implement serialization, a class simply implements the Java.io.Serializable interface.
Serialization does not save and transient variables
Object serialization and deserialization can be implemented using JDK native ObjectOutputStream and ObjectInputStream, and custom serialization strategies can be implemented by calling writeObject and readObject methods.