Java | summary of common Java API manuals

Time:2022-5-14

catalogue

Common API

reference material:

Wiki tutorial

Code tool (recommended)

JavaAPI

1 java.lang

String

Construction method:

  • String(): initializes the newly created string object to represent a null character sequence.

  • String(char[] value): construct a new string from the character array in the current parameter.

  • String(byte[] bytes): construct a new string by decoding the byte array in the current parameter using the platform’s default character set.

    The string written directly in double quotation marks is in the constant pool, and the string written in new is not in the pool. Address values are different.

  • String(byte[] bytes, int offset, int length): construct a new string by decoding the specified byte subarray using the platform’s default character set// Converts a part of a byte array into a string.

  • String(char[] value, int offset, int count): assign a new string that contains characters from a sub array of character array parameters// Converts a part of a character array into a string.

    Convert a part of byte / character array into string offset: start index of array length: number of bytes converted count: number of characters converted

Method of judging function:

  • boolean equals(Objectan Object): compares this string with the specified object.

  • boolean equals IgnoreCase(String another String): compares this string with the specified object, ignoring case.

    Object means “object” and is also a reference type. As a parameter type, it means that any object can be passed into the method.

Method of obtaining function:

  • int length(): returns the length of this string.
  • String concat(String str): concatenates the specified string to the end of the string.
  • char charAt(int index): returns the char value at the specified index.
  • int indexOf(String str): returns the index of the first occurrence of the specified substring within the string.
  • String substring(int beginIndex): returns a substring, intercepting the string from beginindex to the end of the string.
  • String substring(int beginIndex, int endIndex): returns a substring and intercepts the string from beginindex to endindex. Including beginindex and excluding endindex.

Methods of converting functions:

  • char[] toCharArray(): converts this string to a new character array.

  • byte[] getBytes(): convert the string encoding to a new byte array using the platform’s default character set.

  • String replace(CharSequence target, CharSequencere placement): replace the string matching target with the replacement string.

    Charsequence is an interface and a reference type. As a parameter type, you can pass a string object into a method.

How to split functions:

  • String[] split(String regex): splits this string into an array of strings according to the given regex (rule).

    The parameter of the split method is actually a “regular expression”, if it follows the English period “.” For segmentation, you must write “\”.

Static method for converting basic data type to string:

  • String.valueOf(boolean b): converts the boolean variable B to a string.
  • String.valueOf(char c): convert char variable C to a string.
  • String.valueOf(char[] data): convert char array data to string.
  • String.valueOf(char[] data, int offset, int count): convert count elements from data [offset] in char array data into strings.
  • String.valueOf(double d): converts the double variable d to a string.
  • String.valueOf(float f): converts the float variable f to a string.
  • String.valueOf(int i): converts the int variable I to a string.
  • String.valueOf(long l): converts the long variable l to a string.
  • String.valueOf(Object obj): convert obj object into string, equal to obj toString()

Method to convert string to basic data type:

  • Refer to for detailsparseXxxA series of methods.

StringBuilder

java. Lang.stringbuilder string buffer variable character sequence

Construction method:

  • StringBuilder(): construct an empty StringBuilder container.
  • StringBuilder(String str): construct a StringBuilder container and add strings.

Common methods:

  • StringBuilder append(...): adds the string form of any type of data and returns the current object itself.

    Interlock programming: Bu append(“abc”). append(1). append(true). append(8.8). Append (‘medium ‘);

  • String toString(): converts the current StringBuilder object to a string object.

    StringBuilder and string can be converted to each other: String – > StringBuilder: StringBuilder / / StringBuilder – > string: toString

Integer

java. Lang. integer packing and unpacking (other types have similar methods)

Packing (basic type data – > Packing class)

Construction method:

  • Integer(int value): construct a newly assigned integer object that represents the specified int value. (obsolete)
  • Integer(String s): construct a newly allocated integer object that represents the int value indicated by the string parameter.

(the passed string must be a basic type string, otherwise the exception “100” will be thrown, and the exception “a” will be thrown correctly)

Static method:

  • static Integer valueOf(int i): returns an integer instance representing the specified int value.
  • static Integer valueOf(String s): returns an integer object that holds the value of the specified string.

Static method of binary conversion:

  • static String toBinaryString(int i): returns the binary digit string of the number I.
  • static String toOctalString(int i): returns the octal digit string of the number I.
  • static String toHexString(int i): returns the hexadecimal digit string of the number I.
  • static int parseInt(String s): string parametersResolves to a signed decimal integer.
  • static int parseInt(String s, int radix): converts the integer string s (radius is used to indicate that s is a decimal) to a decimal integer.

Unpacking: (data of package – > basic type)

Member method:

  • int intValue(): returns the value of this integer as an int.

parseXxx

Conversion between static method basic type and string

Convert basic type to string

  • The basic type can be directly connected with “; For example: 34 + “

  • static String toString(int i)Returns a string object representing a specified integer.

    The static method toString (parameter) of the wrapper class is not an object class toString () overload

  • static String valueOf(int i)Returns the string representation of the int parameter.

    Static method valueof (parameter) of string class

Convert string to basic type (except character):

  • static byte parseByte(String s): converts the string parameter to the corresponding byte basic type.
  • static short parseShort(String s): converts the string parameter to the corresponding short basic type.
  • static int parseInt(String s): converts a string parameter to the corresponding int base type.
  • static long parseLong(String s): converts the string parameter to the corresponding long basic type.
  • static float parseFloat(String s): converts a string parameter to the corresponding float base type.
  • static double parseDouble(String s): converts the string parameter to the corresponding double basic type.
  • static boolean parseBoolean(String s): converts the string parameter to the corresponding Boolean basic type.

Math

Static constants:

  • static final double PI = 3.141……(accurate to 19 digits)
  • static double exp(double a): returns the number e of Euler, whose value is double.

Basic operation method:

  • static double abs(double a): returns the absolute value of the double value.

  • static double ceil(double a): round up and return the smallest integer greater than or equal to the parameter.

  • static double floor(double a): round down and return an integer less than or equal to the maximum parameter.

  • static long round(double a): returns the long closest to the parameter. (equivalent to rounding method)

  • static int max(int a, int b): returns the larger of a and B.

  • static int min(int a, int b): returns the smaller of a and B.

  • static double cos(double a): returns the triangular cosine of the angle.

  • static double acos(double a): the inverse cosine of the return value; The angle returned is in the range of 0.0 to PI.

  • static double expm1(double x): returns e ^ X – 1.

  • static double log(double a): returns the natural logarithm of the double value (cardinality E).

  • static double log10(double a): returns the base 10 logarithm of the double value.

  • static double pow(double a, doubl b) :a^b

  • static double sqrt(double a): returns the correct rounded positive square root of the double value.

  • static double toDegrees(double angrad): converts an angle measured in radians to an approximate equivalent angle measured in degrees.

  • static double toRadians(double angdeg): converts an angle measured in degrees to an approximate equivalent angle measured in radians.

Object

  • String toString(): returns the string representation of the object.

  • boolean equals(Object obj): indicates whether another object is “equal” to this object.

  • int hasCode(): returns the hash code value of the object.

    When storing custom type elements in the HashSet collection, you need to override the hashcode and equals methods in the object

  • void wait(): causes the current thread to wait before another thread calls the notify() method or notifyall() method of this object.

  • void wait(long timeout): causes the current thread to wait until another thread calls the notify() method or notifyall() method of this object, or before the specified amount of time is exceeded.

  • void wait(long timeout, int nanos): causes the current thread to wait until another thread calls the notify() method or notifyall() method of this object, or another thread interrupts the current thread, or an actual amount of time has been exceeded.

  • void notify(): wakes up a single thread waiting on this object monitor.

  • void notifyAll(): wakes up all threads waiting on this object monitor.

  • Class> getClass(): returns the runtime class of this object.

  • protected Object clone(): creates and returns a copy of this object.

  • protected void finalize(): this method is called by the object’s garbage collector when the garbage collector determines that there are no more references to the object.

System

java. Lang.system contains a large number of static methods

Static fields:

  • static PrintStream err: standard error output stream.
  • static InputStream in: standard input stream.
  • static PrintStream out: standard output stream.

Common methods:

  • static long currentTimeMillis(): returns the current time in milliseconds// Gets the current time in milliseconds.

    Commonly used to test program efficiency

  • static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length): copy the data specified in the array to another array.

    SRC object: source array (original array). SRC posint: source array index start position. Dest object: target array. Dest position: the starting position of the target array index. Length int: number of copied elements.

  • static void setErr(PrintStream err): reassign the standard error output stream.

  • static void setIn(InputStream in): reassign the standard input stream.

  • static void setOut(PrintStream out): reassign the standard output stream.

Throwable

java. Root class of lang.throwable exception

Common methods:

  • void printStackTrace(): print the details of the exception. It includes the type, reason and location of exceptions. Printstacktrace must be used in the development and debugging stages.
  • String getMessage(): get the reason for the exception. When the prompt is given to the user, the error reason will be prompted.
  • String toString(): get the exception type and exception description information (not required).

Thread

Construction method:

  • Thread(): assign a new thread object.
  • Thread(String name): assigns a new thread object with the specified name// thread
  • Thread(Runnable target): a new target object with a specified thread.
  • Thread(Runnable target, String name): assign a new thread object with a specified target and specify a name.

Common methods:

  • String getName(): gets the name of the current thread.
  • void setName(String name): change the thread name to be the same as the parameter name// main
  • void start(): causes this thread to start executing; The Java virtual machine calls the run method of this thread.
  • void run(): the tasks to be performed by this thread define the code here.

Static method:

  • static void sleep(long millis): pauses the currently executing thread for the specified number of milliseconds (temporarily stops execution).
  • static Thread currentThread(): returns a reference to the thread object currently executing.

Runnable / interface

Interface java lang.Runnable

  • abstract void run(): definition of the run method. (there is only one way)

Class

java.lang.Class

How to get the class object

  • static class> forName(String className): returns the class object associated with the class or interface with the given string name.
  • Class name class: obtained through the attribute class of the class name.
  • class> getClass(): returns the runtime class of this object. (object class)

Get member variables:

  • Field[] getFields(): get the member variables of all public modifiers.
  • Field getField(String name): gets the member variable of the public modifier with the specified name.
  • Field[] getDeclaredFields(): get all member variables, regardless of modifiers.
  • Field getDeclaredField(String name): gets the member variable with the specified name.

Get construction methods:

  • Constructor>[] getConstructors(): get the constructor of all public modifiers.
  • Constructor getconstructor (class >... Parametertypes): gets the constructor of the public modifier with the specified name.
  • Constructor getdeclaraedconstructor (class >... Parametertypes): get all construction methods, regardless of modifiers.
  • Constructor>[] getDeclaredConstructors(): gets the constructor of the specified name.

How to get members:

  • Method[] getMethods(): gets the member method of all public modifiers.
  • Method getmethod (string name, class >... Parametertypes): gets the member method of the public modifier with the specified name.
  • Method[] getDeclaredMethods(): get all member methods, regardless of modifiers.
  • Method getdeclaredmethod (string name, class >... Parametertypes): gets the member method with the specified name.

Get full class name:

  • String getName(): returns the entity name (class, interface, array class, basic type or void) represented by this kind of object as string.

How to get class object:

  • Class. Forname ("full class name"): load bytecode file into memory and return class object
    • It is mostly used for configuration files, and the class name is defined in the configuration file. Read files and load classes
  • Class name classGet through the attribute class of the class name:
    • It is used to transfer parameters
  • Object getClass(): the getClass () method is defined in the object class.
    • It is mostly used for obtaining bytecode of objects

*Reflect reflection correlation

Field

java.lang.reflect.Field

Common methods:

  • void set(Object obj, Object value): sets the field represented by this field object on the specified object parameter to the specified new value.
  • Object get(Object obj): returns the value of the field represented by this field on the specified object.
  • void setAccessible(boolean flag): sets the accessible flag of this reflective object to the Boolean value indicated// Ignore the security check of the access modifier, setaccessible (true): violent reflection.

Constructor

java.lang.reflect.Constructor

Common methods:

  • T newInstance(Object... initargs): use the constructor method represented by this constructor object to create and initialize a new instance of the constructor declaration class with the specified initialization parameters.
  • void setAccessible(boolean flag): sets the accessible flag of this reflective object to the Boolean value indicated.

Method

java.lang.reflect.Method

Common methods:

  • Object invoke(Object obj, Object... args): calls the base method represented by this method object on the specified object with the specified parameters.
  • String getName(): returns the name of the method represented by this method object, such as string.

ClassLoader

Abstract class java Lang.classloader class loader

Construction method:

  • protected ClassLoader(): create a classloader that uses a new class loader. This method returns getsystemclassloader () as the parent class loader.
  • protected ClassLoader(ClassLoader parent): creates a new class loader for delegation using the specified parent class loader.
  • protected ClassLoader(String name, ClassLoader parent): creates a new class loader with the specified name and delegates with the specified parent class loader.

Member method:

  • InputStream getResourceAsStream(String name): returns the input stream used to read the specified resource.

  • URL getResource(String name): finds a resource with the given name.

  • Enumeration getResources(String name): finds all resources with the given name.

  • String getName(): if no such loader is specified, the name of such loader or null is returned.

  • protected Object getClassLoadingLock(String className): returns the locked object of the class load operation.

  • protected String findLibrary(String libname): returns the absolute pathname of the native library

  • Protected class > findclass (string name): find binary name with the specified class.


2 java.util

Scanner

Construction method:

  • Scanner(InputStream source): construct a new scanner whose generated values are scanned from the specified input stream.

How to view members:

  • int nextInt(): scan the next mark of the input information into an int value.
  • String next(): gets a string entered by the keyboard.

Obects

  • static boolean equals(Object a, Object b): judge whether two objects are equal.

    Static methods in the objects class tolerate null pointers.

  • static T requireNonNull(T obj): check that the specified reference object obj is not null.

Date (instantaneous)

Represents a specific moment

Constructor:

  • Date(): allocates a date object and initializes it to represent the time (in milliseconds) at which it was allocated// Gets the current time in English format (date date).
  • Date(long date): allocates a date object and initializes it to represent the specified number of milliseconds since the standard base time (January 1, 1970, 00:00:00 GMT)// Millisecond value – > date

Common methods:

  • long getTime(): converts the date object to the corresponding time millisecond value// Date – > millisecond value

Calendar (calendar)

Abstract class java util. Calendar is a calendar class

Calendar static method:

  • static Calendar getInstance(): get a calendar using the default time zone and locale. (get the current time in calendar format.)

Common methods:

  • int get(int field): returns the value of the given calendar field.

  • void set(int field, int value): sets the given calendar field to the given value.

  • void set(int year, int month, int date)Set the values year, month and day of the calendar field_ OF_ MONTH。

  • abstract void add(int field, int amount): adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.

  • Date getTime(): returns a date object representing this calendar time value (the millisecond offset from the epoch to the present)// Calendar – > date

    Int field: field of calendar class / / int field – > calender Member constant

YEAR MONTH DAY_OF_MONTH HOUR HOUR_OF_DAY MINUTE SECOND DAY_OF_WEEK
year Month (starting from 0, can be used with + 1) Day of the month (day) Hour (12 hour system) Hour (24-hour system) branch second Day of the week (day of the week, Sunday is 1, can be – 1)

Random

Construction method:

  • Random(): create a new random number generator.
  • Random(long seed): create a new random number generator using a single long seed.

Member method:

  • int nextInt(): returns the next pseudo-random number, evenly distributing the int value from the sequence of the random number generator.
  • int nextInt(int n): returns a pseudo-random number with an int value between 0 (inclusive) and the specified value n (exclusive).

*Data structure related

Collection / interface

Interface java util. Collection

Defined method:

  • boolean add(E e): adds the given object to the current collection.
  • void clear(): clear all elements in the collection.
  • boolean remove(E e): deletes the given object from the current collection.
  • boolean contains(E e): judge whether the given object is included in the current collection.
  • boolean isEmpty(): judge whether the current collection is empty.
  • int size(): returns the number of elements in the collection.
  • Object[] toArray(): store the elements in the collection into an array.

Method to get iterator:

  • Iterator iterator(): get the iterator corresponding to the collection, which is used to traverse the elements in the collection.

Iterator / interface

Interface java util. Iterator iterator

Common methods:

  • E next(): returns the next element of the iteration.
  • boolean hasNext(): returns true if there are still elements to iterate over.

List / interface

Interface, inherited from the collection interface java util. List

Common methods:

  • void add(int index, E element): adds the specified element to the specified position in the collection.
  • E get(int index): returns the element at the specified location in the collection.
  • E remove(int index): removes the element at the specified position in the list and returns the removed element.
  • E set(int index, E element): replace the element at the specified position in the collection with the specified element, and return the element before the update of the value.
  • default void retainAll(Collection> c): make an intersection between the C set and the set and assign it to the set.

New features of static method jdk9 (premise: the number of elements stored in the collection has been determined):

  • static List of(E… elements): returns an immutable list containing any number of elements.

Arrays

Tool classes related to arrays provide a large number of static methods to realize common operations of arrays

How to manipulate arrays:

  • static String toString(E[] a): returns a string representation of the contents of the specified array.

  • static void sort(E[] a): sorts the specified array in ascending numerical order.

  • static void copyOf(E[] a, int newLength): used to copy the contents of the specified array to achieve the purpose of capacity expansion.

    If it is a custom type, the custom class needs to be supported by the comparable or comparator interface.

ArrayList

java.util.ArrayListSet array structure, slow addition and deletion of elements, fast search

Construction method:

  • ArrayList(): construct a collection with empty content.

Basic format:

  • ArrayList list = new ArrayList<>();

Common methods and traversal: (add, delete, query):

  • Inherited from the list interface.
  • boolean add(E e): adds the specified element to the end of this collection.
  • E remove(int index): removes the element at the specified location in this collection. Returns the deleted element.
  • E get(int index): returns an element at a specified location in this collection. Returns the obtained element.
  • int size(): returns the number of elements in this collection. When traversing a collection, you can control the index range to prevent out of bounds.

LinkedList

java. util. LinkedList linked list structure, which is convenient for adding and deleting elements

Method of head and tail operation:

  • Inherited from the list interface.

  • void addFirst(E e): inserts the specified element at the beginning of this list.

  • void addLast(E e): adds the specified element to the end of this list.

  • void push(E e): pushes an element onto the stack represented by this list.

  • E getFirst(): returns the first element of this list.

  • E getLast(): returns the last element of this list.

  • E removeFirst(): removes and returns the first element of this list.

  • E removeLast(): removes and returns the last element of this list.

  • E pop(): pops an element from the stack represented by this list.

  • boolean isEmpty(): returns true if the list does not contain elements.

Set / interface

Interface inherits from the collection interface.

HashSet

Inherited from set interface.

LinkedHashSet

The linked hash table inherits from the HashSet class.

Collections

java. utils. Collections: collection tool class, which is used to operate on collections

Common functions:

  • static boolean addAll(Collection c, T... elements)Collection:Add some elements t to c elements。

  • static void shuffle(List> list): upset the order, upset the set order.

  • static void sort(List list): sorts the elements in the collection according to the default rule (ascending order).

    Premise of use: the elements stored in the sorted collection must implement comparable. Override the method CompareTo in the interface to define the sorting rules

  • static void sort(List list,Comparator super T> ): sorts the elements in the collection according to the specified rules.

Comparator / interface

Interface java util. Comparatorcomparator

Abstract method definition:

  • abstract int compare(T o1, T o2): o1-o2: sort in ascending order

Comparable/Interface

Interface java Lang. comparable comparator

  • int compareTo(T o): compares the order of this object with the specified object.

    “This” – parameter: sort in ascending order

    Differences between comparator and comparable:

    Comparable: compare yourself (this) with others (parameters). You need to implement the comparable interface and rewrite the comparison rule CompareTo method.

    Comparator: it’s equivalent to finding a third-party referee and comparing two.

Map/Interface

Interface java util. Map collection

Common methods:

  • V put(K key, V value): adds the specified key and specified value to the map collection. Returns the replaced value.

  • V remove(Object key): delete the key value pair element corresponding to the specified key in the map set, and return the value of the deleted element.

  • V get(Object key): get the corresponding value in the map collection according to the specified key.

  • boolean containsKey(Object key): judge whether the set contains the mapping relationship of key value K.

  • boolean containsValue(Object value): determines whether one or more keys in the collection are mapped to the specified value.

  • Set keySet(): get all the keys in the map collection and store them in the set collection.

Method to get all entry objects in the map collection:

  • Set> entrySet(): get the collection of all key value pair objects in the map collection (set collection).

Map.Entry

Key value pair interface java util. Map. EntryIt’s a mapInternal interface of interface

Once the map collection is created, a map will be created in the map collection The entry object is used to record the mapping relationship between key and value (key value pair object and key)

Method for obtaining corresponding key and corresponding value:

  • K getKey(): gets the key in the entry object.
  • V getValue(): gets the value in the entry object.

HashMap

java. util. LinkedHashMap must replicate the hashcode and equals methods of the object

Implement self mapInterface

LinkedHashMap

Ensure order and speed

Inherited from HashMap collection

Stack stack

Stack Java util. Stack

Construction method:

  • Stack(): create an empty stack.

Basic format:

  • Stack stack = new Stack<>();

Member method:

  • boolean empty(): tests whether this stack is empty.

  • E peek(): view the objects at the top of this stack without removing them from the stack.

  • E pop(): removes the object at the top of this stack and returns it as the value of this function.

  • E push(E item): push the item to the top of this stack.

  • int search(Object o): returns the position of the object starting from 1 on this stack.

  • int size(): returns the length of the stack.

Queue / interface

Interface java util. Queue

Construction method:

  • Queue(): create an empty stack.

Basic format:

  • Queue queue= new Queue<>();

Member method:

  • boolean add(E e): inserts the specified element into this queue if you can do so immediately without violating the capacity limit.
  • E element(): Retrieves but does not delete the header of this queue.
  • boolean offer(E e): if it is executed immediately without violating the capacity limit, the specified element is inserted into this queue.
  • E peek(): Retrieves but does not delete the header of this queue, and returns NULL if the queue is empty.
  • E poll(): retrieves and deletes the header of this queue, and returns NULL if the queue is empty.
  • E remove(): retrieves and deletes the header of this queue.

PriorityQueue priority queue

Construction method:

  • PriorityQueue(): create a PriorityQueue with default initial capacity (11) / default ascending order.
  • PriorityQueue(Collection extends E> c): create a PriorityQueue for the elements in the PriorityQueue collection.
  • PriorityQueue(Comparator super E> comparator): create a PriorityQueue with default initial capacity and sort its elements according to the specified comparator.
  • PriorityQueue<>((x, y) -> (int)(y - x)): create a PriorityQueue and arrange it in descending order.

Basic format:

  • PriorityQueue queue= new PriorityQueue<>();

Member method:

  • boolean add(E e): inserts the specified element into this queue if you can do so immediately without violating the capacity limit.
  • void clear(): removes all elements from this priority queue.
  • boolean contains(Object o): returns if this queue contains the specified elementtrue
  • int size(): returns the number of elements in this collection.
  • Object toArray(): returns an array containing all the elements in this queue.
  • E element(): Retrieves but does not delete the header of this queue.
  • boolean offer(E e): if it is executed immediately without violating the capacity limit, the specified element is inserted into this queue.
  • E peek(): Retrieves but does not delete the header of this queue, and returns NULL if the queue is empty.
  • E poll(): retrieves and deletes the header of this queue, and returns NULL if the queue is empty.
  • E remove(): retrieves and deletes the header of this queue.

Lock / interface

Interface java util. concurrent. locks. Lock synchronization lock

  • void lock(): add synchronization lock.
  • void unlock(): release the synchronization lock.

Executors

java. util. concurrent. Executors factory class for production thread pool

  • static ExecutorService newFixedThreadPool(int nThreads): create a thread pool and return the thread pool object. (maximum quantity can be specified)

Executorservice / interface

Interface java util. concurrent. ExecutorService

  • Future> submit(Runnable task): get a thread object in the thread pool and execute it/ Submit a runnable task for execution and return a future representing the task.

    Future interface: used to record the results generated after the execution of thread tasks. Thread pool creation and use.

  • void shut dowm(): start a sequential shutdown to execute previously submitted tasks, but do not accept new tasks.

Properties

java.util.Properties extends Hashtable

Construction method:

  • Properties(): create an empty attribute list.

Basic storage methods:

  • Object setProperty(String key, String value): save a pair of attributes// Call the put method of hashtable.
  • String getProperty(String key): searches for attribute values using the key specified in this attribute list// Find the value value through the key. This method is equivalent to the get (key) method in the map collection.
  • Set stringPropertyNames(): a collection of the names of all keys// Returns the key set in this attribute list, where the key and its corresponding value are strings. This method is equivalent to the keyset method in the map collection.

Flow related methods:

  • void store(OutputStream out, String comments): write the list of properties (key and element pairs) in the properties table to the output stream in a format suitable for loading into the properties table using the load (InputStream) method.

  • void store(Writer writer, String comments): write the property list (key and element pairs) in this properties table to the output character in a format suitable for using the load (Reader) method.

    OutputStream: byte output stream, cannot write Chinese. Writer: character output stream, which can write Chinese. String comments: comments used to explain what the saved file is used for.

  • void load(InputStream inStream): read key value pairs from byte input stream.

  • void load(Reader reader): read the attribute list (key and element pairs) from the input character stream in a simple line oriented format.

    InputStream instream: byte input stream. Key value pairs containing Chinese cannot be read. Reader: character input stream, which can read key value pairs containing Chinese.

Supplier / interface

java.util.function.Supplier

Contains only one parameterless method:

  • T get(): used to get object data of the type specified by a generic parameter.

Consumer / interface

java.util.function.Consumer

Abstract method:

  • void accept(T t): means to consume data of a specified generic type.

Default method andthen:

  • default Consumer andThen(Consumer super T> after): returns a combined consumer that performs this operation in order, and then performs the after operation.

Predict / interface

java.util.function.Predicate

Abstract method:

  • boolean test(T t): scenario used for condition judgment// A method used to judge data of a specified data type.

The default method is and, or, negative:

  • default Predicate and(Predicate super T> other): returns a combined predicate that represents the short-circuit logical and of this predicate and another predicate.
  • static Predicate isEqual(Object targetRef): returns a predicate according to objects Equals (object, object) tests whether the two parameters are equal.
  • default Predicate negate(): returns a predicate that represents the logical negation of this predicate.
  • static Predicate not(Predicate super T> target): returns a predicate that is a negative of the predicate provided.
  • default Predicate or(Predicate super T> other): returns a combined predicate that represents the logical or of the short circuit between this predicate and another predicate.

Function / interface

java.util.function.Function

Abstract method:

  • R apply(T t): get the result of type R according to the parameter of type T.

Default method andthen:

  • default Function andThen(Function super R,? extends V> after): returns the after function that first applies this function to its input, and then applies the after function to the result.
  • default Function compose(Function super V,? extends T> before): returns a composite function that first applies the before function to its input and then applies the function to the result.
  • static Function identity(): returns a function that always returns its input parameters.

Stream/Interface

java.util.stream

Method of obtaining the stream:

  • default Stream stream(): returns a sequential stream
  • default Stream parallelStream(): returns a parallel stream
  • static Stream of(T t)Returns a sequential stream containing a single element.
  • static Stream of(T... values)Returns an ordered stream whose elements are specified values.

Common methods:

  • void forEach(Consumer super T> action): perform an operation on each element of this flow// It can be used to traverse the data in the stream.
  • Stream filter(Predicate super T> predicate): returns a stream consisting of elements of this stream that match this given predicate// Used to filter the data in the stream.
  • Stream map(Function super T, ? extends R> mapper): map elements in a stream to another stream// Returns a stream containing the results of applying the given function to the elements of this stream.
  • long count(): returns the number of elements in this stream.
  • Stream limit(long maxSize): returns a stream composed of elements of this stream, and the truncation length does not exceed maxsize.
  • Stream skip(long n): after discarding the first N element of the stream, return the stream composed of the remaining elements of the stream// Skip the first n elements.
  • static Stream concat(Stream extends T> a, Stream extends T> b): create a deferred connected flow whose elements are all elements of the first flow followed by all elements of the second flow.

3 java.text

DateFormat

The abstraction requires the commonly used subclass Java text. SimpleDateFormat

Construction method of implementation class:

  • SimpleDateFormat(String pattern): construct simpledateformat with the date format symbol of the given schema and default locale// Gets the current time in string format.

Common methods:

  • String format(Date date): formats the date object as a string// Date – > string
  • Date parse(String source): parses a string into a date object in milliseconds// The string – > date / / parse method declares an exception called parseexception

Common format rules are:

y M d D H m s S w W F E zZ
year month Mid moon Mid year sky Time branch second millisecond Mid year week Mid week Mid week week time zone

[external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fyma88h5-1630227054783) (D: \ desktop folder \ school file \ sophomore \ my markdowm notes \ javaapi image \ time format. PNG)]


4 java.io

File

java. io. File is used to create, find and delete files and directories

Static member variables:

  • static String pathSeparator: the path separator associated with the system. For convenience, it is represented as a string.

  • static char pathSeparatorChar: path separator associated with the system.

    Path separator: semicolon; Linux: colon:

  • static String separator: the default name separator associated with the system, which is represented as a string for convenience.

  • static char separatorChar: default name separator associated with the system.

    File name separator windows: backslash \ Linux: forward slash/

Construction method:

  • File(String pathname): create a new file instance by converting the given pathname string to an abstract pathname.

    String pathname: the path name of the string. The path can end with a file or a folder. The path can be a relative path or an absolute path. The path can exist or not exist.

  • File(String parent, String child): creates a new file instance from the parent pathname string and the child pathname string.

  • File(File parent, String child): creates a new file instance from the parent abstract pathname and child pathname strings.

Method of obtaining function:

  • String getAbsolutePath(): returns the absolute pathname string of this file.
  • String getPath(): converts this file to a pathname string// It’s actually the toString method.
  • String getName(): returns the name of the file or directory represented by this file// What you get is the end of the constructor transfer path (file / folder)
  • long length(): returns the length of the file represented by this file// Gets the size of the file specified by the construction method, in bytes.

Method of judging function:

  • boolean exists(): whether the file or directory represented by this file actually exists.
  • boolean isDirectory(): this file indicates whether it is a directory.
  • boolean isFile(): this file indicates whether it is a file.

How to create and delete functions:

  • boolean createNewFile(): creates a new empty file if and only if the file with that name does not already exist.
  • boolean delete(): delete the file or directory represented by this file.
  • boolean mkdir(): create the directory represented by this file// Create a single level empty folder.
  • boolean mkdirs(): create the directory represented by this file, including any required but nonexistent parent directory// You can create either a single level empty folder or a multi-level folder. The path and name of the created folder are given in the construction method (parameters of the construction method).

Traversal of directory:

  • String[] list(): returns a string array representing all sub files or directories in the file directory.
  • File[] listFiles(): returns a file array representing all sub files or directories in the file directory.

Overloaded method of listfiles(): file filter

  • File[] listFiles(FileFilter filter): returns an array of abstract pathnames that represent the files and directories in the directory represented by this abstract pathname that meet the specified filter.

    Filefilter interface: a filter used to abstract pathnames (file objects).

  • File[] listFiles(FilenameFilter filter): returns an array of abstract pathnames that represent the files and directories in the directory represented by this abstract pathname that meet the specified filter.

Filter / interface

Interface java io. Filefilter filter

  • boolean accept(File pathname): test whether pathname should be included in the current file directory. If yes, return true.

OutputStream

Abstract class java io. OutputStream byte output stream

Basic common function method of byte output stream:

  • void close(): close this output stream and free any system resources associated with this stream.
  • void flush(): flush this output stream and force any buffered output bytes to be written out.
  • void write(byte[] b): writes b.length bytes to this output stream from the specified byte array.
  • void write(byte[] b, int off, int len): write len bytes from the specified byte array and output to this output stream from offset off.
  • abstract void write(int b): outputs the specified bytes to the stream.

FileOutputStream

File output stream Java io. FileOutputStream extends OutputStream

Construction method:

  • FileOutputStream(File file): creates a file output stream to write to the file represented by the specified file object.
  • FileOutputStream(String name): creates a file output stream and writes to the file with the specified name.

Construction method 2: data addition and continuation

  • FileOutputStream(File file, boolean append): creates a file output stream to write to the file represented by the specified file object.

  • FileOutputStream(String name, boolean append): creates a file output stream and writes to the file with the specified name.

    Boolean append parameter: true – the created object will not overwrite the source file. Continue to append write data at the end of the file. False – create a new file: overwrite the source file.

Common methods:

  • Inherits from the OutputStream abstract class.
  • write(int b): write out byte method, which can write out byte data one at a time.
  • write(byte[] b): write out the byte array. You can write out the data in the array each time.
  • write(byte[] b, int off, int len): write out the byte array of the specified length, starting from the off index each time, len bytes.

Line breaks in the system:

  • In Windows system, the end of each line is enter + line feed, that is \ R \ n;

  • In UNIX system, there is only newline at the end of each line, that is \ n;

  • In MAC system, the end of each line is carriage return, that is \ R. Unified with Linux from Mac OS X.

    Carriage return \ R: return to the beginning of a line (return)

    Newline character \ n: newline character: next line

InputStream

Abstract class java io. InputStream byte input stream

Basic common function method of byte input stream:

  • void close(): close this input stream and free any system resources associated with this stream.
  • abstract int read(): reads the next byte of data from the input stream.
  • int read(byte[] b): read some bytes from the input stream and store them in byte array B.

FileInputStream

java. io. FileInputStream extensions InputStream

Construction method:

  • FileInputStream(File file): create a FileInputStream by opening a connection to the actual file, which is named by the file object file in the file system.
  • FileInputStream(String name): create a FileInputStream by opening a connection to the actual file, which is named by the pathname name in the file system.

Read byte data:

  • read: read byte method, which can read one byte of data at a time, promote it to int type, read it to the end of the file, and return – 1.
  • read(byte[] b): read with byte array. Each time the length of B is read into the array, return the number of valid bytes read. When reading to the end, return – 1.

Reader

Abstract class java io. Reader character input stream

Basic common function methods of character input stream:

  • void close(): close this flow and free any system resources associated with this flow.
  • int read(): reads a character from the input stream.
  • int read(char[] cbuf): read some characters from the input stream and store them in the character array cbuf.

FileReader

java. io. FileReader extensions reader convenience class for reading character files

Construction method:

  • FileReader(File file): create a new FileReader and give the file object to be read.
  • FileReader(String fileName): create a new FileReader and give the name of the file to be read.
  • read: read character data method. You can read data of one character at a time, promote it to int type, read it to the end of the file, return – 1, and read it circularly.
  • read(char[] cbuf): read using the character array. Each time the length of B is read into the array, return the number of valid characters read. When reading to the end, return – 1.

Writer

Abstract class java io. Writer character output stream

Basic common function method of byte output stream:

  • void write(int c): write a single character.
  • void write(char[] cbuf): write character array.
  • abstract void write(char[] cbuf, int off, int len): write a part of the character array, the start index of the off array, and the number of characters written by Len.
  • void write(String str): write string.
  • void write(String str, int off, int len): write a part of the string, off the start index of the string, and Len the number of characters written.
  • void flush(): flush the buffer of the stream.
  • void close(): close this stream, but refresh it first.

FileWriter

java. io. Filewriter extensions writer is a convenience class that writes characters to a file

Construction method:

  • FileWriter(File file): create a new filewriter and give the file object to be read.
  • FileWriter(String fileName): create a new filewriter and give the name of the file to be read.
  • write(int b): write out character method, one character data can be written out at a time.

Close and refresh:

  • flush: flush the buffer, and the stream object can continue to be used.
  • close: flush the buffer first, and then notify the system to release resources. Stream objects can no longer be used.
  • Write (char [] cbuf) and write (char [] cbuf, int off, int len): write out the character array. You can write out the data in the character array each time. The usage is similar to fileoutputstream.
  • Write (string STR) and write (string STR, int off, int len): write out the string. You can write out the data in the string each time, which is more convenient.

Continuation and line feed:

  • The operation is similar to fileoutputstream.

BufferedOutputStream

java. io. Bufferedoutputstream extensions OutputStream byte buffered output stream

Construction method:

  • BufferedOutputStream(OutputStream out): creates a new buffered output stream to write data to the specified underlying output stream.

  • BufferedOutputStream(OutputStream out, int size): creates a new buffered output stream to write data with the specified buffer size to the specified underlying output stream.

    OutputStream out: byte output stream. We can pass fileoutputstream. The buffer stream will add a buffer to fileoutputstream to improve the writing efficiency of fileoutputstream.

    Int size: Specifies the size of the internal buffer of the buffer stream, not the default.

BufferedInputStream

java. io. Bufferedinputstream extensions InputStream byte buffered input stream

Construction method:

  • BufferedInputStream(InputStream in): create a bufferedinputstream and save its parameter, input stream in, for future use.

  • BufferedInputStream(InputStream in, int size): create bufferedinputstream with the specified buffer size and save its parameter, input stream in, for future use.

    InputStream in: byte input stream. We can pass FileInputStream. The buffer stream will add a buffer to the FileInputStream to improve the reading efficiency of FileInputStream.

BufferedWriter

java. io. Bufferedwriter extensions writer character buffered output stream

Construction method:

  • BufferedWriter(Writer out): create a buffered character output stream using the default size output buffer.

  • BufferedWriter(Writer out, int size): creates a new buffered character output stream using an output buffer of a given size.

    Writer out: character output stream. We can pass the filewriter, and the buffer stream will add a buffer to the filewriter to improve the writing efficiency of the filewriter.

Unique member methods:

  • void newLine(): write a line separator. Different line separators will be obtained according to different operating systems.

    Output statement system out. println(); Is to call the newline () method.

BufferedReader

java. io. BufferedReader extensions reader character buffered input stream

Construction method:

  • BufferedReader(Reader in): create a buffered character input stream using the default size input buffer.

  • BufferedReader(Reader in, int size): creates a buffered character input stream using an input buffer of the specified size.

    Reader in: character input stream. We can pass FileReader, and the buffer stream will add a buffer to FileReader to improve the reading efficiency of FileReader.

Unique member methods:

  • String readLine(): read a text line. Read a row of data.

    Line termination symbol: a line can be considered terminated by one of the following characters: line feed (‘\ n’), carriage return (‘\ R’), or carriage return followed by line feed (\ R \ n). Return value: the string containing the content of the line, without any line terminator. If the end of the stream has been reached, null will be returned.

OutputStreamWriter

java.io.OutputStreamWriter extends Writer

Construction method:

  • OutputStreamWriter(OutputStream in): create a character stream that uses the default character set.

  • OutputStreamWriter(OutputStream in, String charsetName): creates a character stream of the specified character set.

    OutputStream out: byte output stream, which can be used to write converted bytes to a file.

    String charsetname: the name of the specified encoding table, which is not case sensitive. It can be UTF-8 / UTF-8, GBK / GBK Do not specify that UTF-8 is used by default.

InputStreamReader

java.io.InputStreamReader extends Reader

Construction method:

  • InputStreamReader(InputStream in): create a character stream that uses the default character set.

  • InputStreamReader(InputStream in, String charsetName): creates a character stream of the specified character set.

    InputStream in: byte input stream, which is used to read the bytes saved in the file.

ObjectOutputStream

Object serialization stream Java io. Objectoutputstream extends OutputStream writes out the original data types of Java objects to files to realize the persistent storage of objects.

Construction method:

  • ObjectOutputStream(OutputStream out): creates an objectoutputstream that specifies the OutputStream.

    OutputStream out: byte output stream.

Unique method – serialization operation:

  • final void writeObject (Object obj): write out the object method to write out the specified object.

ObjectInputStream

Object’s deserialization stream objectinputstream extends InputStream restores the original data previously serialized with objectoutputstream to an object.

Construction method:

  • ObjectInputStream(InputStream in): creates an objectinputstream that specifies an InputStream.

    InputStream in: byte input stream.

Unique method – deserialization operation:

  • final Object readObject (): read an object. Read objects from objectinputstream.

PrintStream

java. io. Printstream extensions OutputStream printstream

Construction method:

  • PrintStream(String fileName): creates a new print stream with the specified file name.
  • PrintStream(OutputStream out): the destination of the output is a byte output stream.
  • PrintStream(String fileName): the destination of the output is a file path.

5 java.net

Socket

java. net. Socket client

Construction method:

  • Socket(String host, int port): creates a socket object and connects it to the specified port number on the specified host. If the specified host is null, it is equivalent to that the specified address is the loopback address.

    String host: name of the server host / IP address of the server. Int port: the port number of the server.

Member method:

  • InputStream getInputStream(): returns the input stream for this socket. If this socket has an associated channel, all operations of the generated InputStream are also associated with that channel. Closing the generated InputStream will also close the relevant socket.
  • OutputStream getOutputStream(): returns the output stream of this socket. If this socket has an associated channel, all operations of the generated OutputStream are also associated with the channel. Closing the generated OutputStream will also close the relevant socket.
  • void close(): close this socket. Once a socket is closed, it can no longer be used. Closing this socket will also close the related InputStream and OutputStream.
  • void shutdownOutput(): disables the output stream for this socket. Any previously written data will be sent, and then the output stream will be terminated.

ServerSocket

java. net. ServerSocket server

Construction method:

  • ServerSocket(int port): when using this construction method to create a ServerSocket object, you can bind it to a specified port number. The parameter port is the port number.

Member method:

  • Socket accept(): listen and accept the connection, and return a new socket object for communication with the client. This method blocks until a connection is established.

6 java.sql

DriverManager

java. sql. Drivermanager driver management object

Static method:

  • static void registerDriver(Driver driver): register the given driver using drivermanager.

    Write code using:Class.forName("com.mysql.jdbc.Driver");

  • static Connection getConnection(String url): attempt to establish a connection to the given database URL.

  • static Connection getConnection(String url, String user, String password): attempt to establish a connection to the given database URL// Get database connection.

    URL: Specifies the path of the connection [JDBC: mysql://ip Address (domain name): port number / database name], user: user name, password: password.

Connection / interface

java. sql. Interface connection database connection object

Get the object executing SQL:

  • Statement createStatement(): create a statement object to send SQL statements to the database.
  • PreparedStatement prepareStatement(String sql): create a Preparedstatement object to send parameterized SQL statements to the database. (solve the problem of SQL injection)

Management services:

  • void setAutoCommit(boolean autoCommit): set the auto submit mode of this connection to the given state// Start transaction: call this method to set the parameter to false, that is, start the transaction.

  • void commit(): make all changes made since the last commit / rollback permanent and release all database locks currently held by this connection object// Commit the transaction.

  • void rollback(): undo all changes made in the current transaction and release all database locks currently held by this connection object// Rollback transaction.

  • void close(): release the database and JDBC resources of this connection object immediately instead of waiting for them to be released automatically.

Statement / interface

java. sql. Statement object that executes SQL

  • boolean execute(String sql): executes a given SQL statement that may return multiple results// Can execute arbitrary SQL (understand)

  • int executeUpdate(String sql): execute DML (insert, update, delete) statements and DDL (create, alter, drop) statements – not commonly used, and the return value is 0

    Return value: the number of affected rows. You can judge whether the DML statement is executed successfully by the number of affected rows. If the return value > 0, the execution is successful; otherwise, it fails.

  • ResultSet executeQuery(String sql): execute DQL (select) statement, which returns a single resultset object.

  • void close(): occurs when the database and JDBC resources of this statement object are released immediately, rather than waiting for it to shut down automatically.

Resultset / interface

java. sql. Resultset result set object, encapsulating query results

  • boolean next(): the cursor moves down one line to determine whether the current line is at the end of the last line (whether there is data). If yes, it returns false. If not, it returns true.

  • Getxxx (parameter): get data.

    XXX: represents the data type, such as int getint(), string getstring().

    Parameter: int: represents the number of the column, starting from 1, such as getString (1). String: represents the name of the column, such as getdouble (“balance”).

  • void close(): occurs when the database and JDBC resources of this resultset object are released immediately, rather than waiting for it to shut down automatically.

Preparedstatement / interface

java. sql. Preparedstatement object to execute SQL

To ‘?’ Method of assignment:

  • Void setXXX (parameter 1, parameter 2)

    Parameter 1:? The position number of starts from 1. Parameter 2:? Value of

  • ResultSet executeQuery(): execute the SQL query in this Preparedstatement object and return the resultset object generated by the query.

  • int executeUpdate(): execute the Preparedstatement object in the SQL statement, which must be an SQL data manipulation language (DML) statement, such as insert, update or delete; Or SQL statements that do not return anything, such as DDL statements.


7 javax.sql

Datasource / interface

javax. sql. Datasource database connection pool

Member method:

  • default ConnectionBuilder createConnectionBuilder(): create a new connectionbuilder instance.
  • Connection getConnection(): an attempt was made to establish a connection with the data source represented by this datasource object.
  • Connection getConnection(String username, String password): an attempt was made to establish a connection with the data source represented by this datasource object.

Other APIs

*1 com.mchange.v2.c3p0

ComboPooledDataSource

com. mchange. v2. c3p0. Combopooleddatasource database connection pool object (c3p0 package c3p0-0.9.5.2. Jar import required)

Construction method:

  • ComboPooledDataSource()
  • ComboPooledDataSource(String configName)
  • ComboPooledDataSource(boolean autoregister)

Member method:

  • Inherited datasource
  • private void writeObject(ObjectOutputStream oos)
  • private void readObject(ObjectInputStream ois)
  • ClassNotFoundException

*2 com.alibaba.druid.pool

DruidDataSourceFactory

com. alibaba. druid. pool. Druiddatasourcefactory database connection pool factory class (to be imported from Druid package druid-1.0.9.jar)

Member method:

  • protected DataSource createDataSourceInternal(Properties properties)
  • static DataSource createDataSource(Properties properties): gets the connection pool object.
  • static DataSource createDataSource(Map properties)
  • static void config(DruidDataSource dataSource, Map properties)

*3 org.springframework.jdbc.core

JdbcTemplate

org. springframework. jdbc. core. Jdbctemplate template class (implemented with spring)

Construction method:

  • JdbcTemplate()
  • JdbcTemplate(DataSource dataSource)
  • JdbcTemplate(DataSource dataSource, boolean lazyInit)

Member method:

  • update(): method can complete the operations of inserting, updating and deleting data:

  • int update(String sql): this method is the simplest overloaded form of update method. It directly executes the incoming SQL statement and returns the number of affected rows.

  • int update(PreparedStatementCreator psc): this method executes the statement returned from preparedstatementcreator and then returns the number of rows affected.

  • int update(String sql, PreparedStatementSetter pss): this method sets the parameters in the SQL statement through preparedstatementsetter and returns the number of affected rows.

  • int update(String sqlj, Object… args): this method uses object… To set the parameters in the SQL statement. It is required that the parameters cannot be null and returns the number of affected rows.

  • Query () method to handle various query operations on database tables, and encapsulate the results into JavaBean objects:

  • List query(String sql, RowMapper rowMapper): execute the SQL sentence provided by the string type parameter and return a list type result through rowmapper.

  • List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper): create a Preparedstatement object according to the SQL statement provided by the string type parameter, and return the result to the list through rowmapper.

  • List query(String sql, Object[] args, RowMapper rowMapper): use the value of object [] to set the parameter value in SQL. The rowmapper callback method can directly return the data of list type.

  • T queryForObject(String sql, RowMapper rowMapper, Object… args): bind the args parameter to the SQL statement and return a single line record of object type through rowmapper// Query results, encapsulating the results as objects. It is generally used for queries of aggregate functions.

  • Map queryForMap(String sql, Object[] args, int[] argTypes): the query result encapsulates the result set as a map set, the column name as the key, the value as the value, and the record as a map set.

    Note: the length of the result set of this method query can only be 1.

  • List queryForList(String sql, Object[] args, class elementType): this method can return the result of multiple rows, but it must return the list. The ElementType parameter returns the list element type// Query results encapsulate the result set into a list set.

    Note: encapsulate each record into a map set, and then load the map set into the list set.

    Rowmapper: generally, we use the beanpropertyrowmapper implementation class. It can complete the automatic encapsulation of data to JavaBeans.

    New beanpropertyrowmapper (type. Class)


last

Newcomer production, if there are mistakes, welcome to point out, thank you very much!Welcome to follow official account and share some more daily things!If you need to reprint, please mark the source!
Java | summary of common Java API manuals