current position:Home>Java | summary of common API methods in Java

Java | summary of common API methods in Java

2022-01-27 04:02:22 Polychlorinated cyclohexane

Commonly used API

Reference material :

WIKI course

Code tool ( recommend )

JavaAPI

1 java.lang

String

Construction method :

  • String(): Initialize the newly created String object , So that it represents a sequence of empty characters .

  • String(char[] value): Construct a new... From an array of characters in the current argument String.

  • String(byte[] bytes): Construct a new... By decoding the byte array in the current parameter using the platform's default character set String.

    The string written directly in double quotation marks is in the constant pool ,new I'm not in the pool . Different address values .

  • String(byte[] bytes, int offset, int length): Decode the specified... By using the platform's default character set byte Subarray , Construct a new String.// Convert a part of a byte array into a string .

  • String(char[] value, int offset, int count): Assign a new String, It contains characters taken from a subarray of character array parameters .// Convert part of a character array to a string .

    Put bytes / Part of the character array is converted to a string offset: Start index of array length: Number of bytes converted count: Number of characters converted

The way to judge function :

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

  • boolean equalsIgnoreCase(String anotherString): Compare this string with the specified object , Ignore case .

    Object yes ” object ” It means , It's also a reference type . As a parameter type , Indicates that any object can be passed into a method .

How to get the function :

  • int length(): Returns the length of this string .
  • String concat(String str): Connect the specified string to the end of the string .
  • char charAt(int index): Returns the char value .
  • int indexOf(String str): Returns the index of the first occurrence of the specified substring in the string .
  • String substring(int beginIndex): Returns a substring , from beginIndex Start to intercept the string to the end of the string .
  • String substring(int beginIndex, int endIndex): Returns a substring , from beginIndex To endIndex Intercepting string . contain beginIndex, Not included endIndex.

Methods of converting functions :

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

  • byte[] getBytes(): Use the platform's default character set to String Code to a new byte array .

  • String replaceAll(String regex, String replacement): If successful, the replacement string is returned , Failure returns the original string . among regex Is a regular expression that matches this string ;replacement Is the string used to replace each match .

  • String replace(CharSequence target, CharSequencere placement): Will work with target Match strings using replacement String substitution .

    CharSequence It's an interface , It's also a reference type . As a parameter type , You can put String Object passed to method .

Methods of dividing functions :

  • String[] split(String regex): Follow the given regex( The rules ) Split into string arrays .

    split The parameter of the method is actually a “ Regular expressions ”, If according to the English period “.” Segmentation , Must write "\.".

Convert the basic data type to String Of static Method :

  • String.valueOf(boolean b) : take boolean Variable b Convert to string .
  • String.valueOf(char c) : take char Variable c Convert to string .
  • String.valueOf(char[] data) : take char Array data Convert to string .
  • String.valueOf(char[] data, int offset, int count) : take char Array data in from data[offset] Began to take count Elements Convert to string .
  • String.valueOf(double d) : take double Variable d Convert to string .
  • String.valueOf(float f) : take float Variable f Convert to string .
  • String.valueOf(int i) : take int Variable i Convert to string .
  • String.valueOf(long l) : take long Variable l Convert to string .
  • String.valueOf(Object obj) : take obj Object conversion to character string , be equal to obj.toString().

take String A method of converting to a basic data type :

  • Details refer to parseXxx Series method .

StringBuilder

java.lang.StringBuilder String buffer Variable character sequence

Construction method :

  • StringBuilder(): Construct an empty StringBuilder Containers .
  • StringBuilder(String str): Construct a StringBuilder Containers , And add the string to .

Common methods :

  • StringBuilder append(...): Add string form of any type of data , And return the current object itself .

    Interlock programming :bu.append(“abc”).append(1).append(true).append(8.8).append(‘ in ’);

  • String toString(): Will the current StringBuilder Object to String object .

    StringBuilder and String They can switch to each other :String->StringBuilder:StringBuilder//StringBuilder->String:toString

Integer

java.lang.Integer Boxing and UnBoxing ( Other types have similar methods )

Packing ( Basic types of data -> Packaging )

Construction method :

  • Integer(int value): Construct a new assigned Integer object , It means the designated int value .( obsolete )
  • Integer(String s): Construct a new assigned Integer object , It said String The parameter indicates int value .

( String passed , Must be a string of basic type , Otherwise, an exception will be thrown “100” correct “a” Throw exceptions )

Static methods :

  • static Integer valueOf(int i): Returns a specified int It's worth it Integer example .
  • static Integer valueOf(String s): Return to save the specified String The value of the Integer object .

Binary conversion static method :

  • static String toBinaryString(int i): Return to digital i Binary digit string .
  • static String toOctalString(int i): Return to digital i Octal digit string .
  • static String toHexString(int i): Return to digital i Hexadecimal digit string .
  • static int parseInt(String s): The string parameter s Resolve to signed decimal integer .
  • static int parseInt(String s, int radix): The integer string s(radix Used to indicate s It's hexadecimal ) convert to 10 Base integers .

Unpacking :( Packaging -> Basic types of data )

Member method :

  • int intValue(): With int Type returns the Integer Value .

parseXxx

Static methods Conversion between basic types and strings

Convert basic type to string

  • The basic types are directly related to ”” Just connect ; Such as :34+""

  • static String toString(int i) Returns a... That represents a specified integer String object .

    Wrapping static methods of classes toString( Parameters ), No Object Class toString() heavy load

  • static String valueOf(int i) return int String representation of parameter .

    String Class static methods valueOf( Parameters )

Convert string to basic type (Character With the exception of ):

  • static byte parseByte(String s): Convert the string parameter to the corresponding byte Basic types .
  • static short parseShort(String s): Convert the string parameter to the corresponding short Basic types .
  • static int parseInt(String s): Convert the string parameter to the corresponding int Basic types .
  • static long parseLong(String s): Convert the string parameter to the corresponding long Basic types .
  • static float parseFloat(String s): Convert the string parameter to the corresponding float Basic types .
  • static double parseDouble(String s): Convert the string parameter to the corresponding double Basic types .
  • static boolean parseBoolean(String s): Convert the string parameter to the corresponding boolean Basic types .

Math

static const :

  • static final double PI = 3.141……( Accurate to 19 position )
  • static double exp(double a) : return Euler The number of e , Its value double value .

The basic operation method :

  • static double abs(double a): return double The absolute value of value .

  • static double ceil(double a): Rounding up , Returns the smallest integer greater than or equal to the parameter .

  • static double floor(double a): Rounding down , Returns an integer less than or equal to the maximum parameter .

  • static long round(double a): Returns the closest parameter long.( It's equivalent to rounding )

  • static int max(int a, int b) : return a And b The larger value of .

  • static int min(int a, int b): return a And b The smaller value in .

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

  • static double acos(double a): Returns the inverse cosine of the value ; The angle of return is 0.0 To pi Within the scope of .

  • static double expm1(double x): return e^x -1.

  • static double log(double a): return double The natural logarithm of the value ( base e ).

  • static double log10(double a): return double The cardinality of the value 10 logarithm .

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

  • static double sqrt(double a) : return double The correct rounding of the value to the positive square root .

  • static double toDegrees(double angrad): Convert the angle measured in radians to the 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 some other object is associated with this object “ equal ”.

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

    HashSet When a collection holds custom type elements , Need to override the hashCode and equals Method

  • void wait(): This object is called in another thread notify() Method or notifyAll() Before the method , Causes the current thread to wait .

  • void wait(long timeout): This object is called in another thread notify() Method or notifyAll() Method , Or before the specified amount of time , Causes the current thread to wait .

  • void wait(long timeout, int nanos): This object is called in another thread notify() Method or notifyAll() Method , Or some other thread breaks the current thread , Or has exceeded a certain actual amount of time before , Causes the current thread to wait .

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

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

  • Class<?> getClass(): Back here Object Runtime class for .

  • protected Object clone(): Create and return a copy of this object .

  • protected void finalize(): When the garbage collector determines that there are no more references to the object , This method is called by the object's garbage collector .

System

java.lang.System Contains a large number of static methods

Static field :

  • static PrintStream err:“ standard ” Wrong 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 ( The original array ).src Posint: Source array index start .dest Object: Target array .dest Posint: Target array index start .length int: Number of copied elements .

  • static void setErr(PrintStream err): Redistribution “ standard ” Wrong output stream .

  • static void setIn(InputStream in): Redistribution “ standard ” Input stream .

  • static void setOut(PrintStream out): Redistribution “ standard ” Output stream .

Throwable

java.lang.Throwable Abnormal root class

Common methods :

  • void printStackTrace(): Print exception details . Contains the type of exception , reason , Position of appearance , In the development and debugging phases , Have to use printStackTrace.
  • String getMessage(): Get the cause of the exception . When prompted to the user , Just give me the reason for the mistake .
  • String toString(): Get exception type and exception description information ( no need ).

Thread

Construction method :

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

Common methods :

  • String getName(): Get the current thread name .
  • void setName(String name): Change thread name , Make it and parameter name identical .//main
  • void start(): Causes this thread to start executing ;Java The virtual machine calls the run Method .
  • void run(): The tasks to be performed by this thread define the code here .

Static methods :

  • static void sleep(long millis): Pause the currently executing thread for the specified number of milliseconds ( To suspend execution ).
  • static Thread currentThread(): Returns a reference to the currently executing thread object .

Runnable/ Interface

Interface java.lang.Runnable

  • abstract void run():run Method definition .( There's only one way )

Class<T>

java.lang.Class<T>

obtain Class How objects work

  • static class<?> forName(String className): Returns the value associated with a class or interface with a given string name Class object .
  • Class name .class: Through the properties of the class name class obtain .
  • class<?> getClass(): Back here Object Runtime class for . (Object class )

Get member variables :

  • Field[] getFields(): Get all public Modified member variables .
  • Field getField(String name): Gets the... Of the specified name public Modified member variables .
  • Field[] getDeclaredFields(): Get all member variables , Don't think about modifiers .
  • Field getDeclaredField(String name): Gets the member variable of the specified name .

Get constructors :

  • Constructor<?>[] getConstructors(): Get all public Modifies the constructor .
  • Constructor<T> getConstructor( class <?>... parameterTypes): Gets the... Of the specified name public Modifies the constructor .
  • Constructor<T> getDeclaredConstructor( class <?>... parameterTypes): Get all the construction methods , Don't think about modifiers .
  • Constructor<?>[] getDeclaredConstructors(): Gets the constructor with the specified name .

Get member methods :

  • Method[] getMethods(): Get all public Modifies the member method .
  • Method getMethod(String name, class <?>... parameterTypes): Gets the... Of the specified name public Modifies the member method .
  • Method[] getDeclaredMethods(): Get all member methods , Don't think about modifiers .
  • Method getDeclaredMethod(String name, class <?>... parameterTypes): Gets the member method with the specified name .

Get full class name :

  • String getName(): Returns the name of the entity represented by such an object ( class , Interface , Array class , Basic type or void), As String .

obtain Class How objects work :

  • Class.forName(" Full class name "): Load the bytecode file into memory , return Class object
    • More for configuration files , Define the class name in the configuration file . Read the file , Load class
  • Class name .class: Through the properties of the class name class obtain
    • It is mainly used for parameter passing
  • object .getClass():getClass() Method in Object Class defines .
    • It is mainly used for obtaining bytecode of objects

*reflect Reflex 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): This reflects the object's accessible The flag is set to the indicated Boolean value . // Ignore security checks for access modifiers ,setAccessible(true): Violent reflex .

Constructor<T>

java.lang.reflect.Constructor<T>

Common methods :

  • T newInstance(Object... initargs): The constructor method represented by this constructor object , Creates and initializes a new instance of the constructor declaration class using the specified initialization parameters .
  • void setAccessible(boolean flag): This reflects the object's accessible The flag is set to the indicated Boolean value .

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 and use a new class loader ClassLoader This method returns getSystemClassLoader() As a parent loader .
  • protected ClassLoader(ClassLoader parent): Creates a new class loader for delegation using the specified parent class loader .
  • protected ClassLoader(String name, ClassLoader parent): Create a new class loader with the specified name , And delegate with the specified parent loader .

Member method :

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

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

  • Enumeration<URL> getResources(String name): Finds all resources with the given name .

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

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

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

  • protected class <?> findClass(String name): Find the class with the specified binary name .


2 java.util

Scanner

Construction method :

  • Scanner(InputStream source): Construct a new Scanner, The value it generates is scanned from the specified input stream .

View member methods :

  • int nextInt(): Scan the next tag of the input information as a int value .
  • String next(): Get a string entered by the keyboard .

Obects

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

    Objects Static methods in classes tolerate null pointers .

  • static <T> T requireNonNull(T obj): View the specified reference object obj No null.

Date( instantaneous )

Represents a specific moment

Constructors :

  • Date(): Distribute Date Object and initialize this object , To indicate when it was allocated ( Accurate to milliseconds ).// Get English format (Date date ) The current time of .
  • Date(long date): Distribute Date Object and initialize this object , From standard reference time (1970 year 1 month 1 Japan 00:00:00 GMT) Specified number of milliseconds since .// Millisecond value ->Date date

Common methods :

  • long getTime(): Convert Date object to corresponding time millisecond value .//Date date -> Millisecond value

Calendar( The calendar )

abstract class java.util.Calendar It's calendar

Calendar Static methods :

  • 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): Set the given calendar field to the given value .

  • void set(int year, int month, int date) Set the value of the calendar field YEAR , MONTH and DAY_OF_MONTH.

  • abstract void add(int field, int amount): According to calendar rules , Add or subtract a specified amount of time for a given calendar field .

  • Date getTime(): Return a representation of this Calendar Time value ( Millisecond offset from epoch to present ) Of Date object .// The calendar ->Date date

    int field: Fields of calendar class //int field -> Calender. Member constants

YEAR MONTH DAY_OF_MONTH HOUR HOUR_OF_DAY MINUTE SECOND DAY_OF_WEEK
year month ( from 0 Start , Sure +1 Use ) The day of the month ( What's the number ) when (12 hourly ) when (24 hourly ) branch second The days of the week ( What day of the week , Sunday is 1, Sure -1 Use )

Random

Construction method :

  • Random(): Create a new random number generator .
  • Random(long seed): Using a single long Seed creates a new random number generator .

Member method :

  • int nextInt(): Returns the next pseudo-random number , Evenly distributed from the sequence of the random number generator int value .
  • int nextInt(int n): Returns a pseudo-random number , The scope is 0( Include ) And the specified value n( barring ) Between int value .

* Data structure correlation

Collection/ Interface

Interface java.util.Collection

Method of definition :

  • boolean add(E e): Add the given object to the current collection .
  • void clear() : Empty all elements in the collection .
  • boolean remove(E e): Delete the given object in the current collection .
  • boolean contains(E e): Determine whether the current collection contains the given object .
  • boolean isEmpty(): Determine whether the current set is empty .
  • int size(): Returns the number of elements in the collection .
  • Object[] toArray(): Put the elements in the set , Store in array .

Method to get iterator :

  • Iterator iterator(): Get the iterator corresponding to the collection , Used to traverse elements in a collection .

Iterator/ Interface

Interface java.util.Iterator iterator

Common methods :

  • E next(): Returns the next element of the iteration .
  • boolean hasNext(): If there are still elements that can iterate , Then return to true.

List/ Interface

Interface , Inherited from Collection Interface java.util.List

Common methods :

  • void add(int index, E element): Will specify the element , Add to the specified location in the collection .
  • E get(int index): Returns the element at the specified location in the collection .
  • E remove(int index): Remove the element at the specified location in the list , What is returned is the removed element .
  • E set(int index, E element): Replace the element at the specified location in the collection with the specified element , Returns the pre update element of the value .
  • default void retainAll(Collection<?> c): take c A set intersects with the set , And assign to the set .

Static methods JDK9 New characteristics ( Premise : The number of elements stored in the collection has been determined ):

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

Arrays

Tool classes related to arrays , Provides a number of static methods , Implement common array operations

How to operate the array :

  • static String toString(E[] a): Returns a string representation of the contents of a 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's a custom type , Then this custom class needs to have Comparable perhaps Comparator Interface support .

ArrayList

java.util.ArrayList<E> aggregate Array structure , Slow addition and deletion of elements , Quick search

Construction method :

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

The basic format :

  • ArrayList<String> list = new ArrayList<>();

Common methods and traversal :( increase 、 Delete 、 check ):

  • Inherited from List Interface .
  • boolean add(E e): Add the specified element to the end of this collection .
  • E remove(int index): Remove the element at the specified location in this collection . Returns the deleted element .
  • E get(int index): Returns the element at the specified location in this collection . Return the element obtained .
  • int size(): Returns the number of elements in this collection . When traversing a collection , You can control the index range , To prevent cross-border .

LinkedList

java.util.LinkedList Chain table structure , Convenient elements add 、 Deleted sets

The method of head and tail operation :

  • Inherited from List Interface .

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

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

  • void push(E e): Push elements onto the stack represented by this list .

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

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

  • E removeFirst(): Remove and return the first element of this list .

  • E removeLast(): Remove and return the last element of this list .

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

  • boolean isEmpty(): If the list does not contain elements , Then return to true.

Set/ Interface

Interface Inherited from Collection Interface .

HashSet

Inherited from Set Interface .

LinkedHashSet

Chain hash table Inherited from HashSet class .

Collections

java.utils.Collections: Collection tool class , Used to manipulate a collection

Common functions :

  • static <T> boolean addAll(Collection<T> c, T... elements): To gather Collection<T> c Add some elements to T… elements.

  • static void shuffle(List<?> list) : Out of order , Disorganize the order of assembly .

  • static <T> void sort(List<T> list): Set the elements in the collection according to the default rules ( Ascending ) Sort .

    Use the premise : The elements stored in the sorted collection , Must be realized Comparable, Override methods in the interface compareTo Define the rules for sorting

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

Comparator/ Interface

Interface java.util.Comparator<T> The comparator

Abstract method definition :

  • abstract int compare(T o1, T o2):o1-o2: Ascending sort

Comparable<T>/ Interface

Interface java.lang.Comparable The comparator

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

    own "this"- Parameters : Ascending sort

    Comparator and Comparable The difference between :

    Comparable: own (this) And others ( Parameters ) Compare , I need to realize Comparable Interface , Rewrite the comparison rules compareTo Method .

    Comparator: It's equivalent to finding a third-party referee , Compare the two .

Map<T>/ Interface

Interface java.util.Map aggregate

Common methods :

  • V put(K key, V value): Add the specified key and specified value to Map Collection . Returns the replaced value value .

  • V remove(Object key): Set the key value corresponding to the specified key to the element in Map Delete... From the collection , Returns the value of the deleted element .

  • V get(Object key): According to the specified key , stay Map Get the corresponding value in the collection .

  • boolean containsKey(Object key): Determine whether the collection contains key values k The mapping relation of .

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

  • Set<K> keySet(): obtain Map All the keys in the set , Store in Set Collection .

  • V getOrDefault(Object key, V defaultValue): When Map There's this in the collection key when , Just use this key Of Value value ; If not, use the default value defaultValue.

Map Get all from the collection Entry Object method :

  • Set<Map.Entry<K,V>> entrySet(): Get Map Collection of all the key value pairs in the collection (Set aggregate ).

Map.Entry

Key value pair interface java.util.Map.Entry<K,V> yes Map<T> The internal interface of an interface

When Map Set one to create , Then it will be in Map Create a... In the collection Map.Entry object , Used to record keys and values ( Key value pair object , The mapping relationship between keys

Method for obtaining corresponding key and corresponding value :

  • K getKey(): obtain Entry Key in object .
  • V getValue(): obtain Entry Value in object .

HashMap

java.util.LinkedHashMap Must copy the object's hashCode and equals Method

Come true from Map<T> Interface

LinkedHashMap

Keep order , And fast

Inherited from HashMap aggregate

Stack Stack

Stack java.util.Stack<E>

Construction method :

  • Stack(): Create an empty stack .

The basic format :

  • Stack<Object> stack = new Stack<>();

Member method :

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

  • E peek(): View the objects at the top of this stack , Without removing it from the stack .

  • E pop(): Remove the object at the top of this stack , And return the object as the value of this function .

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

  • int search(Object o): Returns the from... Of the object on this stack 1 Starting position .

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

Queue queue / Interface

Interface java.util.Queue<E>

Construction method :

  • Queue(): Create an empty stack .

The basic format :

  • Queue<Object> queue= new Queue<>();

Member method :

  • boolean add(E e): Inserts the specified element into this queue , If you can do this now , Without violating the capacity limit .
  • E element(): Retrieve but not delete the header of this queue .
  • boolean offer(E e): If you execute immediately without violating the capacity limit , Then the specified element is inserted into this queue .
  • E peek(): Retrieves but does not delete the header of this queue , If this queue is empty , Then return to null.
  • E poll(): Retrieve and delete the headers of this queue , If this queue is empty , Then return to null .
  • E remove(): Retrieve and delete the headers 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 Of the elements in the collection PriorityQueue.
  • PriorityQueue(Comparator<? super E> comparator): Create a with default initial capacity PriorityQueue, And sort its elements according to the specified comparator .
  • PriorityQueue<>((x, y) -> (int)(y - x)) : Create a PriorityQueue, And in descending order .

The basic format :

  • PriorityQueue<Object> queue= new PriorityQueue<>();

Member method :

  • boolean add(E e): Inserts the specified element into this queue , If you can do this now , Without violating the capacity limit .
  • void clear(): Remove all elements from this priority queue .
  • boolean contains(Object o): If the queue contains the specified element , Then return to true .
  • int size(): Returns the number of elements in this collection .
  • Object toArray(): Returns an array containing all the elements in this queue .
  • E element(): Retrieve but not delete the header of this queue .
  • boolean offer(E e): If you execute immediately without violating the capacity limit , Then the specified element is inserted into this queue .
  • E peek(): Retrieves but does not delete the header of this queue , If this queue is empty , Then return to null.
  • E poll(): Retrieve and delete the headers of this queue , If this queue is empty , Then return to null .
  • E remove(): Retrieve and delete the headers of this queue .

Lock/ Interface

Interface java.util.concurrent.locks.Lock Synchronization lock

  • void lock(): Add synchronization lock .
  • void unlock(): Release the synchrolock .

Executors

java.util.concurrent.Executors Factory class of production thread pool

  • static ExecutorService newFixedThreadPool(int nThreads): Creating a thread pool , Return thread pool object .( You can specify the maximum number )

ExecutorService/ Interface

Interface java.util.concurrent.ExecutorService

  • Future<?> submit(Runnable task): Get a thread object in the thread pool , And implement ./ To submit a Runnable Tasks are used to perform , And returns a Future.

    Future Interface : Used to record the results of thread tasks after execution . Thread pool creation and use .

  • void shut dowm(): Start a sequence close , Perform previously submitted tasks , But don't take on new tasks .

Properties

java.util.Properties extends Hashtable

Construction method :

  • Properties() : Create an empty list of properties .

Basic storage methods :

  • Object setProperty(String key, String value): Save a pair of properties .// call Hashtable Methods put.
  • String getProperty(String key): Use the key specified in this property list to search for property values .// adopt key find value value , This method is equivalent to Map In the collection get(key) Method .
  • Set<String> stringPropertyNames(): The set of names of all keys .// Returns the key set in this property list , Where the key and its corresponding value are strings , This method is equivalent to Map In the collection keySet Method .

Flow related methods :

  • void store(OutputStream out, String comments): To be fit for use load(InputStream) Method is loaded to Properties The format in the table , Put this Properties List of properties in table ( Bond and element pair ) Write output stream .

  • void store(Writer writer, String comments): To be fit for use load(Reader) The format of the method , Put this Properties List of properties in table ( Bond and element pair ) Write output characters .

    OutputStream: Byte output stream , Cannot write Chinese .Writer writer: Character output stream , Can write in Chinese .String comments: notes , Used to explain what the saved file is for .

  • void load(InputStream inStream): Read key value pairs... From byte input stream .

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

    InputStream inStream: Byte input stream , Cannot read key value pairs containing Chinese .Reader reader: Character input stream , Can read key value pairs containing Chinese .

Supplier/ Interface

java.util.function.Supplier<T>

Contains only one parameterless method :

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

Consumer/ Interface

java.util.function.Consumer<T>

Abstract method :

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

The default method andThen:

  • default Consumer<T> andThen(Consumer<? super T> after): Returns a combined Consumer , It does this in sequence , And then execute after operation .

Predicate/ Interface

java.util.function.Predicate<T>

Abstract method :

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

The default method and,or,negate:

  • default Predicate<T> and(Predicate<? super T> other): Returns a combined predicate , Short circuit logic that represents this predicate and another predicate AND.
  • static <T> Predicate<T> isEqual(Object targetRef): Returns a predicate , according to Objects.equals(Object, Object) Test whether the two parameters are equal .
  • default Predicate<T> negate(): Returns the predicate that represents the logical negation of this predicate .
  • static <T> Predicate<T> not(Predicate<? super T> target): Returns the predicate , The predicate is the negation of the predicate provided .
  • default Predicate<T> or(Predicate<? super T> other): Returns a combined predicate , Represents the short circuit logic between this predicate and another predicate OR.

Function/ Interface

java.util.function.Function<T,R>

Abstract method :

  • R apply(T t): According to the type T Parameter get type of R Result .

The default method andThen:

  • default <V> Function<T,V> andThen(Function<? super R,? extends V> after): Returns the... That first applies this function to its input after function , And then after Function applied to the result .
  • default <V> Function<V,R> compose(Function<? super V,? extends T> before): Returns a composite function , This function will first before Function is applied to its input , Then apply this function to the result .
  • static <T> Function<T,T> identity(): Returns a function that always returns its input parameters .

Stream<T>/ Interface

java.util.stream

Get the method of stream :

  • default Stream<E> stream() : Returns a sequence stream
  • default Stream<E> parallelStream() : Return a parallel stream
  • static <T> Stream<T> of(T t) Returns the order that contains a single element Stream .
  • static <T> Stream<T> of(T... values) Returns an ordered stream whose elements are specified values .

Common methods :

  • void forEach(Consumer<? super T> action): Perform operations on each element of this flow .// It can be used to traverse the data in the stream .
  • Stream<T> filter(Predicate<? super T> predicate): Returns a stream consisting of elements of this flow that match the given predicate . // Used to deal with Stream The data in the stream is filtered .
  • <R> Stream<R> map(Function<? super T, ? extends R> mapper): Map elements in a stream to another stream .// Back to a stream , The stream contains the results of applying the given function to the elements of the stream .
  • long count(): Returns the number of elements in this stream .
  • Stream<T> limit(long maxSize): Returns the stream made up of the elements of this stream , The truncation length shall not exceed maxSize .
  • Stream<T> skip(long n): At the first drop stream n After the element , Returns a stream consisting of the rest of the elements of this stream . // Skip the former n Elements .
  • static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b): Create a deferred connection flow , Its elements are all the elements of the first stream , Followed by all the elements of the second stream .

3 java.text

DateFormat

abstract Need common subclasses java.text.SimpleDateFormat

Implementation class construction method :

  • SimpleDateFormat(String pattern): Construct... With the date format symbols of the given pattern and default locale SimpleDateFormat.// Gets the current time in string format .

Common methods :

  • String format(Date date): take Date Object is formatted as a string .//Date date -> character string
  • Date parse(String source): Parse string to Date object ( Number of milliseconds ).// character string ->Date 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 In the middle of the moon Mid year when branch second millisecond Mid year week Mid week Mid month week week The time zone

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-fYMa88h5-1630227054783)(D:\ Desktop folder \ School documents \ Sophomore \ my Markdowm note \JavaAPI picture \ Time format .png)]


4 java.io

File

java.io.File For creating files and directories 、 Search and delete operations

Static member variable :

  • static String pathSeparator: System related path separator , For convenience , It's represented as a string .

  • static char pathSeparatorChar: System related path separator .

    Path separator windows: A semicolon ; linux: The colon :

  • static String separator: The default name separator associated with the system , For convenience , It's represented as a string .

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

    File name separator windows: The backslash \ linux: Forward slash /

Construction method :

  • File(String pathname): Create a new... By converting the given pathname string to an abstract pathname File example .

    String pathname: Path name of string , The path can end with a file , It can also end with a folder , The path can be relative path , It could be an absolute path , The path can exist , It can also be non-existent .

  • File(String parent, String child): Create a new... From the parent pathname string and the child pathname string File example .

  • File(File parent, String child): Create a new... From the parent abstract pathname and child pathname strings File example .

How to get the function :

  • String getAbsolutePath(): Back here File The absolute pathname string for .
  • String getPath(): Put this File Convert to pathname string .// In fact, that is tostring Method .
  • String getName(): Back here File Represents the name of a file or directory .// What you get is the end of the constructor transfer path ( file / Folder )
  • long length(): Back here File Represents the length of the file .// Gets the size of the file specified by the constructor , In bytes .

The way to judge function :

  • boolean exists(): this File Indicates whether the file or directory actually exists .
  • boolean isDirectory(): this File Indicates whether the is a directory .
  • boolean isFile(): this File Is it a document .

Create methods to delete features :

  • boolean createNewFile(): If and only if a file with that name does not already exist , Create a new empty file .
  • boolean delete(): Delete this File Represents a file or directory .
  • boolean mkdir(): Create this File Table of contents .// Create a single level empty folder .
  • boolean mkdirs(): Create this File Table of contents , Include any required but nonexistent parent directories .// You can create a single level empty folder , You can also create multi-level folders , The path and name of the created folder are given in the construction method ( Parameters of construction method ).

Directory traversal :

  • String[] list(): Return to one String Array , It means that we should File All sub files or directories in the directory .
  • File[] listFiles(): Return to one File Array , It means that we should File All the sub files or directories in the directory .

listFiles() Overload method of : File filter

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

    FileFilter Interface : Used for abstract pathnames (File object ) Filter .

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

Filter/ Interface

Interface java.io.FileFilter filter

  • boolean accept(File pathname): test pathname Should it 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 the output stream and release any system resources associated with the stream .
  • void flush(): Flush this output stream and force any buffered output bytes to be written out .
  • void write(byte[] b): take b.length Byte writes this output stream from the specified byte array .
  • void write(byte[] b, int off, int len): Write... From the specified byte array len byte , From the offset off Start output to this output stream .
  • abstract void write(int b): Output the specified byte 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 File represented by object .
  • FileOutputStream(String name): Create a file output stream to write 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 File represented by object .

  • FileOutputStream(String name, boolean append): Create a file output stream to write to the file with the specified name .

    boolean append Parameters :true- Creating an object does not overwrite the source file , Continue to append write data at the end of the file .false- Create a new file : Overwrite source file .

Common methods :

  • Inherited from OutputStream abstract class .
  • write(int b): Write byte method , One byte of data can be written out at a time .
  • write(byte[] b): Write an array of bytes , You can write out the data in the array every time .
  • write(byte[] b, int off, int len) : Write a byte array of the specified length , Write every time from off Index start ,len Bytes .

Line breaks in the system :

  • Windows In the system , Each line ends with a carriage return + Line break , namely \r\n;

  • Unix In the system , Each line ends with a new line , namely \n;

  • Mac In the system , Each line ends with a carriage return , namely \r. from Mac OS X Start with Linux Unified .

    A carriage return \r: Go back to the beginning of the line (return)

    A newline \n: A newline : The next line (newline)

InputStream

abstract class java.io.InputStream Byte input stream

Basic common function method of byte input stream :

  • void close(): Close the input stream and release any system resources associated with the stream .
  • abstract int read(): Read the next byte of data from the input stream .
  • int read(byte[] b): Read some bytes from the input stream , And store them in a byte array b in .

FileInputStream

java.io.FileInputStream extends InputStream File input stream

Construction method :

  • FileInputStream(File file): Create a... By opening a connection to the actual file FileInputStream , This file is created by File object file name .
  • FileInputStream(String name): Create a... By opening a connection to the actual file FileInputStream , This file is made up of pathnames in the file system name name .

Read byte data :

  • read: Read byte method , One byte of data can be read at a time , Upgrade to int type , Read to the end of the file , return -1.
  • read(byte[] b): Use byte array to read , Each read b The length of bytes into the array , Returns the number of valid bytes read , When reading to the end , return -1.

Reader

abstract class java.io.Reader Character input stream

The basic common function method of character input stream :

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

FileReader

java.io.FileReader extends Reader Convenient class for reading character files

Construction method :

  • FileReader(File file): Create a new FileReader , Given the... To read File object .
  • FileReader(String fileName): Create a new FileReader , Give the name of the file to read .
  • read: Method of reading character data , One character of data can be read at a time , Upgrade to int type , Read to the end of the file , return -1, Cyclic reading .
  • read(char[] cbuf): You can write the data in the character array each time , Each read b The length of characters into the array , Returns 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 ,off Start index of array ,len The number of characters written .
  • void write(String str): Write string .
  • void write(String str, int off, int len): Write a part of the string ,off Start index of string ,len The number of characters written .
  • void flush(): Refresh the buffer of the stream .
  • void close(): Close this stream , But refresh it first .

FileWriter

java.io.FileWriter extends Writer Write out the convenience class of characters to the file

Construction method :

  • FileWriter(File file): Create a new FileWriter, Given the... To read File object .
  • FileWriter(String fileName): Create a new FileWriter, Give the name of the file to read .
  • write(int b): How to write characters , One character data can be written at a time .

Close and refresh :

  • flush: Refresh buffer , Stream objects can continue to use .
  • close: Refresh the buffer first , Then inform the system to release resources . Stream objects can no longer be used .
  • write(char[] cbuf) and write(char[] cbuf, int off, int len): You can write the data in the character array each time , You can write the data in the character array each time , Usage is similar. FileOutputStream.
  • write(String str) and write(String str, int off, int len): Write a string , You can write the data in the character array each time , More convenient .

Continuation and line feed :

  • The operation is similar to FileOutputStream.

BufferedOutputStream

java.io.BufferedOutputStream extends OutputStream Byte buffered output stream

Construction method :

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

  • BufferedOutputStream(OutputStream out, int size) : Create 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 on FileOutputStream, The buffer stream will give FileOutputStream Add a buffer , Improve FileOutputStream Write efficiency of .

    int size: Specifies the size of the internal buffer of the buffer stream , Do not specify default .

BufferedInputStream

java.io.BufferedInputStream extends InputStream Byte buffered input stream

Construction method :

  • BufferedInputStream(InputStream in): Create a BufferedInputStream And save its parameters , Input stream in, For future use .

  • BufferedInputStream(InputStream in, int size): Create... With the specified buffer size BufferedInputStream And save its parameters , Input stream in, For future use .

    InputStream in: Byte input stream . We can pass on FileInputStream, The buffer stream will give FileInputStream Add a buffer , Improve FileInputStream Read efficiency .

BufferedWriter

java.io.BufferedWriter extends 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): Create a new buffered character output stream that uses an output buffer of a given size .

    Writer out: Character output stream . We can pass on FileWriter, The buffer stream will give FileWriter Add a buffer , Improve FileWriter Write efficiency of .

Unique membership methods :

  • void newLine(): Write a line separator . According to different operating systems , Get different line separators .

    Output statement System.out.println(); It's called newLine() Method .

BufferedReader

java.io.BufferedReader extends 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): Create a buffered character input stream using the specified size input buffer .

    Reader in: Character input stream . We can pass on FileReader, The buffer stream will give FileReader Add a buffer , Improve FileReader Read efficiency .

Unique membership methods :

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

    Line terminator : A line is considered terminated by one of the following characters : Line break (’\n’)、 enter (’\r’) Or just follow the line after returning (\r\n). Return value : String containing the contents of the line , Does not contain any line terminators , If the end of the stream has been reached , Then return to null.

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): Create a character stream for the specified character set .

    OutputStream out: Byte output stream , It can be used to write the converted bytes to the file .

    String charsetName: The specified encoding table name , Case insensitive , It can be utf-8/UTF-8,gbk/GBK,… Do not specify default use UTF-8.

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): Create a character stream for the specified character set .

    InputStream in: Byte input stream , Used to read the bytes saved in the file .

ObjectOutputStream

Object's serialization stream java.io.ObjectOutputStream extends OutputStream take Java The original data type of the object is written out to the file , Implement persistent storage of objects .

Construction method :

  • ObjectOutputStream(OutputStream out): Create a specification OutputStream Of ObjectOutputStream.

    OutputStream out: Byte output stream .

Unique method - Serialization operation :

  • final void writeObject (Object obj) : Write the object method , Write out the specified object .

ObjectInputStream

Object's deserialization stream ObjectInputStream extends InputStream Will be used before ObjectOutputStream Serialized raw data is restored to objects .

Construction method :

  • ObjectInputStream(InputStream in): Create a specification InputStream Of ObjectInputStream.

    InputStream in: Byte input stream .

Unique method - Deserialization operation :

  • final Object readObject () : Read an object . from ObjectInputStream Read the object .

PrintStream

java.io.PrintStream extends OutputStream Print stream

Construction method :

  • PrintStream(String fileName): Create a new print stream with the specified filename .
  • 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): Create a socket object and connect it to the specified port number on the specified host . If specified host yes null, It is equivalent to specifying the address as the return address .

    String host: The name of the server host / Server's IP Address .int port: Port number of the server .

Member method :

  • InputStream getInputStream(): Returns the input stream for this socket . If so Scoket With associated channels , Then it generates InputStream All operations of are also associated with the channel . Close the generated InputStream It will also close the relevant Socket.
  • OutputStream getOutputStream(): Returns the output stream for this socket . If so Scoket With associated channels , Then it generates OutputStream All operations of are also associated with the channel . Close the generated OutputStream It will also close the relevant Socket.
  • void close(): Close this socket . Once a socket Shut down , It can no longer be used . Close this socket It will also close the relevant InputStream and OutputStream.
  • void shutdownOutput(): Disable the output stream for this socket . Any previously written data will be sent , The output stream is then terminated .

ServerSocket

java.net.ServerSocket Server side

Construction method :

  • ServerSocket(int port): Use this construction method to create a ServerSocket Object time , You can bind it to a specified port number , Parameters port It's the port number .

Member method :

  • Socket accept(): Listen and accept connections , Back to a new Socket object , For communicating with clients . This method will block until a connection is established .

6 java.sql

DriverManager

java.sql.DriverManager Drive management objects

Static methods :

  • static void registerDriver(Driver driver): Use DriverManager Register the given driver .

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

  • static Connection getConnection(String url): Try to build a database with a given one URL The connection of .

  • static Connection getConnection(String url, String user, String password): Try to build a database with a given one URL The connection of . // Get database connection .

    url: Specify 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

Access to perform sql The object of :

  • Statement createStatement(): Create a Statement object , Is used to SQL Statements are sent to the database .
  • PreparedStatement prepareStatement(String sql): Create a PreparedStatement object , Used to parameterize SQL Statements are sent to the database .( solve sql Injection problem )

Manage affairs :

  • void setAutoCommit(boolean autoCommit): Set the auto-commit mode for this connection to the given state .// Open transaction : Call this method to set the parameter to false, That is, start the transaction .

  • void commit(): Make since last submission / All changes made since rollback become permanent , And release the Connection Object currently holds all database locks .// Commit transaction .

  • void rollback(): Undo all changes made in the current transaction , And release the Connection Object currently holds all database locks .// Roll back the transaction .

  • void close(): Release this immediately Connection Object database and JDBC resources , Instead of waiting for them to release automatically .

Statement/ Interface

java.sql.Statement perform sql The object of

  • boolean execute(String sql) : Perform a given SQL sentence , This statement may return multiple results . // You can do whatever you want sql ( understand )

  • int executeUpdate(String sql) : perform DML(insert、update、delete) sentence 、DDL(create,alter、drop) sentence - Not commonly used , The return value is 0

    Return value : Number of rows affected , It can be judged by the number of rows affected DML Is the statement executed successfully , Return value >0 Then the execution is successful , conversely , The failure .

  • ResultSet executeQuery(String sql) : perform DQL(select) sentence , This statement returns a single ResultSet object .

  • void close(): Release this immediately Statement Object database and JDBC resources , Instead of waiting for it to close automatically .

ResultSet/ Interface

java.sql.ResultSet Result set object , Encapsulate query results

  • boolean next(): Move the cursor down one line , Determine whether the current line is the end of the last line ( Is there any data ), If it is , Then return to false, If not, return true.

  • getXxx( Parameters ): get data .

    Xxx: Representative data type , Such as :int getInt(),String getString() .

    Parameters :int: Represents the number of the column , from 1 Start , Such as :getString(1).String: Name of representative column , Such as :getDouble(“balance”).

  • void close(): Release this immediately ResultSet Object database and JDBC resources , Instead of waiting for it to close automatically .

PreparedStatement/ Interface

java.sql.PreparedStatement perform sql The object of

to ’?' The method of assignment :

  • void setXxx( Parameters 1, Parameters 2)

    Parameters 1:? Location number of from 1 Start . Parameters 2:? Value

  • ResultSet executeQuery(): Execute this PreparedStatement Object SQL Inquire about , And return the query generated ResultSet object .

  • int executeUpdate(): Execute in this SQL sentence PreparedStatement object , It has to be a SQL Data manipulation language (DML) sentence , such as INSERT , UPDATE or DELETE ; Or not return anything SQL sentence , for example DDL sentence .


7 javax.sql

DataSource/ Interface

javax.sql.DataSource Database connection pool

Member method :

  • default ConnectionBuilder createConnectionBuilder(): Create a new ConnectionBuilder example .
  • Connection getConnection(): Try this DataSource Object to establish a connection to the data source represented by .
  • Connection getConnection(String username, String password): Try this DataSource Object to establish a connection to the data source represented by .

other API

*1 com.mchange.v2.c3p0

ComboPooledDataSource

com.mchange.v2.c3p0.ComboPooledDataSource Database connection pool object ( Need to be C3P0 package c3p0-0.9.5.2.jar Import )

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 ( Need from Druid package druid-1.0.9.jar Import )

Member method :

  • protected DataSource createDataSourceInternal(Properties properties)
  • static DataSource createDataSource(Properties properties): Get 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 ( use Spring Realization )

Construction method :

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

Member method :

  • update(): Method to complete the insertion 、 Update and delete data :

  • int update(String sql): This method is the simplest update Method overload form , It executes the incoming... Directly SQL sentence , And return the number of rows affected .

  • int update(PreparedStatementCreator psc): The method executes from PreparedStatementCreator The returned statement , Then return the number of rows affected .

  • int update(String sql, PreparedStatementSetter pss): The method is passed by PreparedStatementSetter Set up SQL Parameters in statement , Returns the number of affected rows .

  • int update(String sqlj, Object… args): This method uses Object… Set up SQL Parameters in statement , The required parameter cannot be NULL, And return the number of rows affected .

  • query() Method to handle various query operations on database tables , And encapsulate the results as JavaBean object :

  • List query(String sql, RowMapper rowMapper): perform string Provided by type parameter SQL sentence , And I've been RowMapper Return to one List Result of type .

  • List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper): according to String Provided by type parameter SQL Sentence creation PreparedStatement object , adopt RowMapper Return the result to List in .

  • List query(String sql, Object[] args, RowMapper rowMapper): Use Object[] Set the value of SQL Parameter value in , use RowMapper The callback method can directly return List Data of type .

  • <T> T queryForObject(String sql, RowMapper rowMapper, Object… args): take args Parameters bound to SQL In the sentence , And pass RowMapper Return to one Object Single line record of type .// Query results , Encapsulate the results as objects . Generally used for queries of aggregate functions .

  • Map<String,Object> queryForMap(String sql, Object[] args, int[] argTypes): Query results encapsulate the result set as map aggregate , Name as key, Take the value as value Encapsulate this record as a map aggregate .

    Be careful : The result set length of this method query can only be 1.

  • <T> List<T> queryForList(String sql, Object[] args, class<T> elementType): This method can return the results of multiple rows , But it must be a return list ,elementType The parameter returns List Element type .// Query results encapsulate the result set as list aggregate .

    Be careful : Encapsulate each record as a Map aggregate , then Map The collection is loaded into List Collection .

    RowMapper: Generally we use BeanPropertyRowMapper Implementation class . Can complete data to JavaBean Automatic encapsulation of .

    new BeanPropertyRowMapper< type >( type .class)


Last

New people make , If there is a mistake , Welcome to point out , Be deeply grateful !
Welcome to the official account , Will share something more everyday !
If you want to reprint , Please mark the source !

copyright notice
author[Polychlorinated cyclohexane],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270402161928.html

Random recommended