JAVA -- API oriented interface

Keywords: Java

abnormal

1. Concept

  • An abnormal condition has occurred in the program

2.throwable type

1. Compile time exception Error

  • Generally refers to syntax errors, which can be corrected according to the compiler prompt

2. Runtime Exception

  • Tested abnormality

     The compiler proposes exception handling
     Common detected abnormalities
     	ClassNotFoundException
     	IOException
     	SQLException
     	FileNotFoundException
    
  • Non inspected abnormality

     The code does not need to force capture processing
     Common non inspected abnormalities
     	RuntimeException
     	NullPointerException
     	IndexOutOfBoundsException
     	ArrayIndexOutBoundsException
     	StringIndexOutOfBoundsException
    

3. The parent class of all exceptions is Throwable

  • Throwable -> Exception/Error

3.try{}catch(){}

1. Format

try{
	One line can also be multiple lines
}catch(Exception type variable name){
	Prompt statement
}
  • try: monitor code blocks with possible exceptions
    Once an exception is found in the try block, it will jump out of the try block directly
  • Catch: catch the specified exception type object
  • getMessage() output error
  • printStackTrace() gets the red error message
  • try{}catch {} will add extra overhead

4.finally

  • No matter what happens to try/catch, the finally block will execute

  • Code blocks that must be executed, such as closing a resource (first judge whether the resource is empty)

  • Application scenario
    When an exception occurs, the program may be interrupted unexpectedly, and some occupied resources cannot be cleaned up

  • be careful
    1.finally must be used with the try block and cannot exist alone
    2.finally can also be executed after return

5.throws

  • The method does not handle the check exception (catch block). At this time, you must throw out the method and hand it over to the calling function for processing (try catch)

     Calling function: the method that calls this function
    
  • Format: throws exception class name

  • be careful
    Must follow the parenthesis of the method
    Try not to throw an exception on the main method
    Throw exception out of method

6.throw

  • Manually throw an exception in a method
  • Format: throw exception object
  • be careful
    Exceptions must be handled
    Processing method 1: try catch
    Processing method 2: throws an exception

7. User defined exception

8. Inheritance structure system of exception class

  • The base class of the Exception is Exception, and all exceptions must inherit it directly or indirectly

  • Exception is inherited by most exceptions

  • Most exceptions do not override methods

9. Common exception types

  • Exception is the root class of the exception hierarchy

  • RuntimeException is the base class for many Java.lang exceptions

  • ArithmeticException arithmetic exception

  • IllegalArgumentException method received an illegal parameter

  • ArrayIndexOutOfBoundsException array subscript out of bounds

  • Null pointerexception access null reference

  • ClassNotFoundException could not load the required class

  • ClassCastException type conversion exception

  • NumberFormatException failed to convert string to number or number formatting exception

  • Root class of IOException I/O exception

  • FileNotFoundException file not found

  • End of EOFEException file

10. Exception types of JDBC programming

  • SQLException
  • SQLWarning

java.lang

Note: base package – therefore, the guide package does not need to be displayed

1. Packaging

1. General

  • In order to perform more and more convenient operations on basic data types, Java provides corresponding class types for each basic type

2.boolean–Boolean
3.byte–Byte
4.char–Character

  • Construction method

     public Character(char value)
    
  • Member method

     public static boolean isUpperCase(char ch)
     	Determines whether a given character is uppercase
     public static boolean isLowerCase(char ch)
     	Determines whether a given character is lowercase
     public static boolean isDigit(char ch)
     	Determines whether a given character is a numeric character
     public static char toUpperCase(char ch)
     	Converts the given character to uppercase
     public static char toLowerCase(char ch)
     	Converts the given character to lowercase
    

5.short–Short
6.int–Integer

Integer a3 = 100;// Auto boxing: convert basic data type to wrapper class object int i=
a3;// Automatic unpacking: unpacks packaging class objects into a basic data type

  • Field summary

     public static final int MAX_VALUE
     	obtain int Type Max
     public static final int MIN_VALUE
     	obtain int Type minimum
    
  • Construction method

     public Integer(int value)
     public Integer(String s)
     	Note: this string must consist of numeric characters
    
  • Member method

     Binary conversion
     	Base conversion
     		public static String toBinaryString(int i)
     		public static String toOctalString(int i)
     		public static String toHexString(int i)
     	Decimal to other decimal
     		public static String toString(int i,int radix)
     	Other to decimal
     		public static int parseInt(String s,int radix)
     Type conversion
     	public static int parseInt(String s)
     		Converts a string type to an integer
     Save value
     	public static Integer valueOf(String s)
     		Return to save the specified String Value of Integer object
     	public static Integer valueOf(String s,int radix)
     		Return a Integer Object, which saves the specified value when parsing with the cardinality provided by the second parameter String Values extracted from
     	public static Integer valueOf(int i)
     		Returns a value representing the specified int Value Integer example
    

7.long–Long
8.float–Float
9.double–Double

2. Automatic disassembly box

  • Auto boxing: converts a base type to a packing type

  • Automatic unpacking: convert the package type to the basic type

Integer i = new Integer(100);
Integer i = 100; (automatic packing) no error will be reported
i += 100; (automatic unpacking) will not report an error
Note: i is not equal to null, otherwise an error is reported (null pointer exception). It is recommended to add an if statement for judgment

3.String class

String: can be regarded as an array of characters

1.String API

  • The string literal "abc" can also be regarded as a string object

  • String is a constant and cannot be changed once assigned (please understand)

     String s = "hello";
     s += "world";  //+=String splicing
     Q: s What is the result?
     result: helloworld
     
     String s = "hello";
     	In the stack String s
     	Find string constant pool in method area"hello",If yes, return directly; if not, create one"hello"
     	Method area"hello"To the stack String s
     s += "world";
     	because s The value of cannot be changed. Find it in the method area"world",If not, create a new one"world",But it doesn't make sense
     	Create a new space in the method area helloworld Splice together, and pay the address value of this space to String s
    
  • The value cannot be changed instead of referenced

2. Construction method

  public String()
	Nonparametric structure
  public String(byte[] bytes)
	Convert byte array to string
  public String(byte[] bytes,int offset,int length)
	Converts a part of a byte array into a string
  public String(char[] value)
	Convert character array to string
  public String(char[] value,int offset,int count)
	Converts a part of a character array into a string
  public String(String original)
	Converts a string constant value to a string

3. Method

  • Judgment function

    boolean equals(Object obj)
     Compare whether the string contents are the same, case sensitive
    boolean equalsIgnoreCase(String str)
     Compare whether the string contents are the same, ignoring case
    boolean contains(String str)
     Judge whether a large string contains a small string. Note that the string is a whole
    boolean startsWith(String str)
     Determines whether a string begins with a specified string
    boolean endsWith(String str)
     Determines whether a string ends with a specified string
    boolean isEmpty()
     Determine whether the string is empty
    

be careful
1. Empty string content: indicates that the object exists but has no content

String s = “”; S can call objects

2. String object is empty: none of the objects exist

String s = null; s is not callable

  • Get function

    int length()
     Get string length
    char charAt(int index)
     Gets the character at the specified index position
     The index of the first element is 0
    int indexOf(int ch)
     Gets the index of the first occurrence of the specified character in this string
     Why int Type instead of char Type?'a'And 97 can represent a
    int indexOf(String str)
     Gets the index of the first occurrence of the specified string in this string
    int indexOf(int ch,int fromIndex)
     Gets the index of the first occurrence of the specified character in this string after the specified position
    int indexOf(String str,int fromIndex)
     Gets the index of the specified string for the first time since the specified position in the string
    String substring(int start)
     Intercepts the string from the specified position to the end by default
    String substring(int start,int end)
     Intercept the string package from the specified position to the end of the specified position. The left package does not contain the right package
    
  • Conversion function

    byte[] getBytes()
     Converts a string to a byte number
    char[] toCharArray()
     Converts a string to a character array
    static String valueOf(char[] chs)
     Convert character array to string
    static String valueOf(int i)
     take int Convert data of type to string
      be careful: String Class valueOf Method can convert any type of data into a string
    String toLowerCase()
     Convert string to lowercase
    String toUppweCase()
     Convert string to uppercase
    String concat(String str)
     Concatenate strings  +In fact, it can also be spliced
    
  • Other functions

    Replace function
      String replace(char old,char new)
      String replace(String old,String new)
    Remove spaces at both ends of the string
      String trim()
    Compares two strings in dictionary order
      int compareTo(String str)
     	Case sensitive
      int compareToIgnoreCase(String str)
     	Case insensitive
     Each character is compared in order. If it is the same, it will be compared with the next one. If it is exactly the same, it will return 0; If different characters are subtracted, the subtracted value is returned
    

4.StringBuffer class

1. Function: solve the problem of time-consuming and waste of space when creating a String class for each String splicing

  • You cannot directly assign a value of type String to StringBuffer

2. Thread safety

  • Security - synchronization

    When I am operating, others can't operate (withdraw money from the bank)
    data security

  • Unsafe - out of sync
    High efficiency, news, forums and so on

3. The difference between StringBuffer and String

  • StringBuffer: thread safe variable string, that is, variable length and content

  • String: length and content are immutable

4. Construction method

public StringBuffer()
	Nonparametric construction method
public StringBuffer(int capacity)
	String buffer object with specified capacity
public StringBuffer(String str)
	Specifies the string buffer object for the string content

5. Method function

  • Add function

     public Stringbuffer append(String str)
     	String buffer is used to improve the efficiency of string operation 
     	Adds any type to the string buffer and returns the string buffer itself
     public Stringbuffer insert(int offset,String str)
     	Inserts any type of data into the string buffer at the specified location, and returns the string buffer itself
    
  • Delete function

     public StringBuffer deleteCharAt(int index)
     	Deletes the character (one) at the specified position and returns itself
     public StringBuffer delete(int start,int end)
     	Delete the content from the specified location to the end of the specified location, and return to itself
     	Package left not package right
    
  • Replace function

     public StringBuffer replace(int start,int end,String str)
     	The string from the specified position to the end of the specified position is str replace
     	Package left not package right
    
  • Reverse function

     public StringBuffer reverse()
     	input abc,output cba
    
  • Interception function

     public String substring(int start)
     public String substring(int start,int end)
     Note that the return value type is String type,That is, do not change the created StringBuffer Object content
    

6. Interview questions

  • The difference between string, StringBuffer and StringBuilder

     String The content is immutable, StringBuffer,StrignBuilder Are variable in content
     StringBuffer It is synchronous, data security and low efficiency; StringBuilder Out of sync, unsafe data and high efficiency
    
  • The difference between StringBuffer and array

     StringBuffer The final data is a string data
     Arrays can hold multiple data types, but they must be of the same data type
     Without considering multithreading StringBuilder More widely used
    

5.StringBuilder class

  • Thread unsafe

6. Inter class conversion

1. Conversion between string and StringBuffer

  • Why convert

    A – B in order to use the functions of B
    B – a the result is type A, so turn back

  • You cannot pay the value of a string directly to StringBuffer
    StringBuffer s = “hello”; wrong

  • Implement conversion

    S–SB
    Method 1: through construction method
    Sreing s = "hello"
    StringBuffer sb = new StringBuffer(s)
    Method 2: use the append() method
    Sreing s = "hello"
    StringBuffer sb = new StringBuffer()
    sb.append(s)

    SB–S
    Method 1: through construction method
    StringBuffer buffer = new StringBuffer("java")
    String str = new String(buffer)
    Method 2: through toString() method
    StringBuffer buffer = new StringBuffer("java")
    String str = buffer.toString()

2. Conversion between string and int

  • i–S

    Mode 1
    int number = 100;
    String s = "" + number;
    Mode II
    int number = 100;
    String s = String.valueOf(number);
    Method 3: int – Integer – String
    int number = 100;
    Integer i = new Integer(number);
    String s = i.toString();
    Mode 4
    int number = 100;
    String s = Integer.toString(number);

  • S–i

    Method 1: String – Integer – int
    String s = "100";
    Integer i = new Integer(s);
    int x = i.intValue();
    Mode II
    String s = "100";
    int y = Integer.parseInt(s);

7.Object class

1. Description

  • All classes directly or indirectly inherit from the Object class

  • There is only one construction method of Object class, and it is a parameterless construction

  • Pay attention to the use of these methods

  • native is not implemented in Java

2. Methods to master

public String toString()
	Returns the string representation of the object. The default is the full path of the class+'@'+Hexadecimal representation of hash value
	This representation is meaningless, so the general subclass will override the method
public boolean equals(Object obj)
	Function: compare whether two objects are the same. By default, the address value is the same, and String Type compares whether the string contents are the same
	However, it is meaningless to compare address values, so the general subclass will override this method
	When this method is overridden, hashCode It is also necessary to rewrite
public int hashCode()
	Returns the hash value of the object, which is not the actual address value, but can be understood as the address value
	Note: the hash value is a value calculated according to the hash algorithm, which is related to the address
  • There is no need to always create the same object -- in this case, you need to override hashCode() equals()

3. Methods to understand

public final Class getClass()
	Returns the bytecode file object of the object
protected void finalize()
	Function: used for garbage collection at uncertain time
protected Objectclone()
	Object cloning can be realized, including data replication of member variables, but it is different from two references pointing to the same object

4. Attention

  • Directly output an object name. In fact, the toString() method of the object is called by default

  • ==Difference from equals()

     ==
      Basic type: compares whether the values are the same
      Reference type: compares whether the address values are the same
     equals()
      You can only compare reference types. By default, you compare whether the address values are the same, but you can override this method according to your needs
    

8.Math class

1. Overview: methods including basic mathematical operations

2. Member variables

public static final double PI
public static final double E

3. Membership method

public static int abs(int a)
	absolute value
public static double cell(double a)
	Round up
public static double floor(double a)
	Round down,The decimal part takes 0
public static int max(int a,int b)
	Maximum
public static int min(int a,int b)
	minimum value
public static double pow(double a,double b)
	a of b pow 
public static double random()
	random number[0.0,1.0)
public static int round(float a)
	rounding
public static int round(double a)
	rounding
public static double sqrt(double a)
	Positive square root

9.Class

1. Concept: Class instances represent classes and interfaces in running Java applications

2. No common construction method

  • The Class object is automatically constructed by the Java virtual machine and by calling the defineClass method in the Class loader when the Class is loaded
  • Every running Class will have a Class instance, which is obtained by the virtual machine

3. Obtain XXXXX

  • Get the Class instance of a Class
    Method 1: reflect Class.forName()
    Method 2: object name. getClass()
    Method 3: class name.class

  • Get inheritance relation getSuperClass()

  • Get all public fields getFields()

  • Get all fields (including private) getdeclaraedfields()

  • Get all methods getdeclaraedmethods()

4. Create object

  • newInstance()

5. Activation

  • invoke()

10.System class

1. Overview: contains some useful class fields and methods, which cannot be instantiated
2. Membership method

public static void gc()
	Run the garbage collector
public static void exit(int atatus)
	Terminate the currently running virtual machine
	Parameters are used as status codes
		Non-zero indicates abnormal termination
		0 Indicates normal
public static long currentTimeMillis()
	Returns the current time in milliseconds
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
	Copies an array from the specified source array, starting at the specified location and ending at the specified location of the target array

java.util

Note: tool kit – must be guided

1.Random class

1. Overview: used to generate random numbers

2. Construction method

public Random()
	No seed is given, but the default seed is used, which is the millisecond value of the current seed, that is, the seed is different each time
public Random(long seed)
	Give the specified seed

3. Membership method

public int nextInt()
	Returned is int Random number in range
public int nextInt(int n)
	Returned is[0,n)Random number in range

2.Scanner class

1. Basic format

public boolean hasNextXXX()
	Determine whether there is another input item XXX Representative type
	If you need to judge whether to include the next string, you can save XXX
public XXX nextXXX()
	Get next entry XXX Same meaning
 In order to make the procedure more rigorous, use this method, but the usual writing method can also be used
  • By default, Scanner uses spaces, carriage returns, etc. as separators

2. Common methods

public int nextint()
	obtain int value
public String nextine()
	Get string

3. Attention

  • When using the same sc to obtain a value, if an int is obtained first and a String is obtained, the String type will be replaced by the Enter key after int input

  • terms of settlement

     Create two different sc
     (recommend)Get all the data as a string, and then cast what type you need
    

3.Date class

1. Overview: indicates a specific moment, accurate to milliseconds

2. Construction method

public Date()
	Creates a date object based on the current default millisecond value
public Date(long date)
	Creates a date object based on the given millisecond value
	Application scenario: the last modification time of the file is the number of milliseconds. You need to create a date object through the constructor

3. Membership method

public long getTime()
	Gets the time in milliseconds
public void setTime(long time)
	Set time

4. Convert a millisecond value to Date

1.Construction method
2.setTime(long time)

4.DateFormat class

1. Overview: the date and string are formatted and parsed, but they are abstract classes, so the specific subclass SimpleDateFormat is used

2. Construction method of simpledateformat

SimpleDateFormat()
	Default mode
	Thread unsafe
SimpleDateFormat(String pattern)
	Given mode
	SimpleDateFormat("yyyy-MM-dd hh:mm:ss E")

3.SimpleDateFormat method

format(Date date)
	Will one Date Format as date/Time string
parse(String s)
	Parse the text of the string and generate Date
	When parsing, the string format must be and SimpleDateFormat(String pattern)Match patterns in

5.Calendar Class

1. Overview: for a specific moment and a group of shapes, such as year day_ OF_ Provides methods for conversion between calendar fields such as month

2.Calendar c = Calendar.getInstance();// You cannot directly create new. You must call this method to create an instance object

3. Membership method

public void set(int field,int value)
	field - Given calendar field
	value - The value to set for a given calendar field
public int get(int field)
	Returns the value of the given calendar field
	Each calendar field in the calendar class is a static member variable and is int type
public void add(int field,int amount)
	Adds or subtracts the specified amount of time for a given calendar field
		c.add(Calendar.YEAR, 2);
		c.add(Calendar.YEAR, -4);

6.Arrays class

1. Overview: tool class for array operation

2. Membership method

public static String toString(int[] a)
	Convert array to string
	Array elements can be output with output statements
	Convert to string[Element 1,Element 2,...]Look like
public static void sort(int[] a)
	Sort array
	By initials ASCLL code
public static void sort(Object[] a)
	Sort an array of objects
	All elements in the array must implement Comparable Interface
	Students []s = new Students[5];
    Arrays.sort(s);//All elements in the array must implement the Comparable interface
Students implements Comparable{
	rewrite compareTo method
}
public static int binarySearch(int[] a,int key)
	Binary search
public static <T> List <T> asList(T...s)
	Convert array to collection

7. Generics

1. Concept: a special type that postpones the type definition until the object is created or the method is called

2. Format: < reference data type > – yes

3. Benefits

  • Advance run-time issues to compile time

  • Casts are avoided

  • The program design is optimized to solve the problem of yellow warning line

4. Application

  • Generic class

     Format: public class Class name<Generic type 1,...>
     Note: generic types must be reference types
    
  • generic method

     Format: public <generic types > Return type method name(Generic type 1,...)
    
  • generic interface

     Format: public interface Interface name<Generic type 1,...>
    

5. Generic advanced wildcard

  • <?>
     Any type is ambiguous Object And arbitrary Java class
    
  • <? extends E>
     Downward limit E And its subclasses
    
  • <? super E>
     Up limit E And its parent class
    

8.Collection collection

1. Concept: the meaning of a set is similar to that of an array

2. Differences between arrays and sets

  • Length difference

     Fixed array length
     Variable set length
    
  • Different content

     Arrays contain elements of the same type
     Collection can store different types of elements
    
  • The data types of stored elements are different

     Arrays can store basic data types or reference data types
     Collection can only contain reference data types
    

3.Collection function overview

  • Create object first

     Collection A = new ArrayList()
     Note that directly outputting a statement A,You can output all the elements in the collection
    
  • Add function

     boolean add(Object obj)
     	Add an element
     boolean addAll(Collection c)
     	Add all elements of a collection
    
  • Delete function

     void clean()
     	Remove all elements
     boolean remove(Object o)
     	Remove an element
     boolean removeAll(Collection c)
     	Remove the elements of a collection. As long as one element is removed, it is removed
    
  • Judgment function

     boolean contains(Object o)
     	Determines whether the collection contains the specified element
     boolean containsAll(Collection c)
     	Judge whether the set contains the specified set elements. Only including all elements is called including
     boolean isEmpty()
     	Determine whether the collection is empty
    
  • Get function (iterator)

     Iterator<E> iterator()
     	Special traversal method of collection
     	Iterators depend on collections. You should create collections before using iterators
     	method
     		Object next()
     			Get the element and move to the next element, that is, the next time you use it to get the element, you will get the next element
     			Do not use it multiple times it.next()method
     		hasNext()
    
  • Length function

     int size()
     	Number of elements
     Interview questions
     	Is there an array length()method?
     	Is there a string length()method?
     	Is there a collection length()method?
    
  • Intersection function

     boolean retainAll(Collection c)
     	Take the elements you have and I want to save to the object calling the method, that is.Left of
     	Suppose there are two sets AB,A yes B Do intersection A.retainAll(B),The final results are saved in A In, B unchanged
     	The return value represents A Has it changed
    
  • Convert collection to array

     Object[] toArray()
     	Form: Object[] obj = A.toArray()
     	The collection can be converted into an array and then traversed
     	be careful
    
  • In the Collection class, Collection is the top-level interface of the Collection

4. To use a collection

  • Create collection object

  • Create element object

  • Add element to collection

  • Traversal set

     Get iterator object from collection object
     By iterator object hasNext()Method to determine whether there are elements
     By iterator object next()Method to get the element and move to the next location
    

5. Son of collection – list & set

  • List
    1. Characteristics of list set: orderly (the stored and retrieved elements are the same) + repeatable
    2.List specific functions

(1) Add function void add(int index,Object element)
Add an element at the specified position and add the element after index
Be careful not to cross the line
(2) Get function Object get(int index)
Gets the element at the specified location
(3) List iterator listiterator()
List collection specific iterators
(4) Delete function Object remove(int index)
Delete the element according to the index and return the deleted element
(5) Modify function Object set(int index,Object element)
Modify the element according to the index and return the modified element

3. Member method of listiterator interface

(1)boolean hasPrevious()
Determine whether there are elements
(2)Object previous()
Get previous element
(3) Note: ListIterator can realize reverse traversal, but it must traverse forward before reverse traversal. Therefore, it is generally meaningless and not used, but it has more methods than Iterator, and Iterator can not realize reverse order. List Iterator, but it is generally not used

  • Set
    1. Characteristics of set
    Out of order (the stored and retrieved elements are inconsistent)
    Although it is out of order, it has its own order. Note that the output order is exactly the same as its output order
    Unique (non repeatable)

6. Your son

  • ArrayList

(1) The underlying structure is an object array, which is fast to query and slow to add and delete
(2) Thread unsafe (out of sync), high efficiency
(3) 1.5x capacity expansion
(4) Method
add(T t)
get(int index)
remove(int index)
isEmpty()
clear()
size()

  • Vector

(1) The underlying structure is an array, which is fast to query and slow to add and delete
(2) Thread safe (synchronous), inefficient
(3) 2X expansion
(4) Unique function
Add function
public void addElement(Object obj) -- add() instead
Get function
public Object elementAt(int index) -- get() instead
public Enumeration elements() -- replaced by Iterator iterator()
boolean hasMoreElements() -- replaced by hasNext()
Object nexterelement() -- replaced by next()

  • LinkedList

(1) The underlying structure is a double linked list, which is slow to query and fast to add and delete
(2) Unsafe thread and high efficiency
(3) Unique function
Add function
public void addFirst(Object e)
public void addLast(Object e)
Get function
public Object getFirst()
public Object getLast()
Delete function
public Object removeFirst()
public Object removeLast()

7. The son of set - HashSet class

  • disorder
  • Traversal output cannot use for loops (unordered), but enhanced for loops can
  • Create an array to store elements. The remainder of elements divided by the total number of elements is stored in the array with index
  • Hash Collisions

Concept: there is something on the address, and another one needs to be saved
The zipper method completely avoids hash conflict. After the conflict, it is directly stored behind the existing elements of the array to establish a single linked list

8. Static import

Format: import static package name, class name, method name

You can export directly to the method level

  • be careful

     Method must be static
     If there are multiple static methods with the same name, you don't know who to use
    

9. Variable parameters

  • Use: when defining a method without knowing how many parameters to define

Format: modifier return value type method name (data type... Variable name) {}

  • be careful

     This variable is actually an array
     If a method has variable parameters and has multiple parameters, the variable parameters are placed last
    

9. Map < K, V > key value pair

The key cannot be repeated. A key (k) corresponds to a value, and the value (v) can be repeated
1. Subclass HashMap

  • Thread unsafe

  • put(K,V)

(1)size()
(2) Get all key values: set = map. Keyset();
(3) Get all values: Collection col = map.values();
(4) Get the Set view Set of key value pair mapping: Set < map. Entry < integer, student > > entries=
map.entrySet()

for(Map.Entry<Integer, Student> m:map.entrySet()){
 	System.out.println(m.getKey()+" "+m.getValue()); 
} 
Allow one-time insertion of keys and values
  • Its key value can be null
  • Subclasses rely on hashCode(),equals() to find duplicate elements

2. Subclass HashTable

  • Thread safety
  • Hashtable.keySet() descending order
  • Properties

load() loads configuration information from the file input stream
store() is saved to the file output stream
getProperty()
setProperty(key,value) adds a key value

  • None of the key values can be null

3. Subclass TreeMap

  • TreeMap.keySet() ascending
  • Default sort

java.io

Permanent data storage

1.File class

The instance of File class is immutable; That is, once created, the abstract pathname represented by the File object will never change

1. Field

  • Path separator;

     pathSeparator
     pathSeparatorChar
    
  • Name separator\

     separator
     separatorChar
    

2. Constructor

File(String parent,String child)
File(File parent,String child)
File(String name)

3. Method

obtain
	Get file name
		getName()
	Get path name
		getPath()
	Get absolute path name
		getAbsolutePath()
	Return parent path
		getParent()
	parent object
		getParentFile().getName()
Judge file status
	non-existent
		exists()
	existence
		file
			isFile()
		folder
			isDirectory()
other
	File Bytes
		length()
	create a file
		Note: it is created only when it does not exist
		createNewFile()
File src=new File("D:/java/workspace/D1/io.txt");
boolean flag= src.createNewFile();
	Delete existing files
		delete()
Create directory
	mkdir()
		If the parent directory does not exist, the creation fails
	mkdirs()
		If the parent directory does not exist, it will be created together
 list
	List child names
		list()
			bin
	List subordinates File object
		listFile()
			D:\java\workspace\D1\bin
	List all drive letters
		(static)listRoots()
			D:\
	String array receive
dir=new File("D:/java/workspace/D1");
String [] subNames=dir.list();

2. Byte stream

1. Concept: read or write data from the stream in bytes (8 bits), which is usually used to process binary files

2.InputStream byte input stream

  • abstract class
  • Function: read data byte by byte into memory
  • common method

(1) available() returns an estimate of the number of bytes that can be read in the input stream
(2) close() closes the input stream and frees the system resources associated with the stream
(3) (abstract)read() reads the next byte of data from the current location input stream
(4) read() reads the next byte of data from the input stream
(5) read(byte []b) reads b.length byte data from the current location input stream and stores them in byte array B
(6) read(byte []b,int off,int len) reads len bytes of data from the current location, stores it in b, and starts writing from b[off] (byte [] b, int off, int len)

  • Subclass

(1) AudioInputStream
(2) Bytearrayinputstream (character array input stream)
(3) FileInputStream (file input stream) is responsible for the stream of sequential input operations on local disk files
Constructor (file) + (String name)
(4) Filterinputstream
(5) Objectinputstream (object input stream)
(6) Datainputstream (basic data type input stream)
(7) PipedInputStream
(8) Sequenceinputstream links multiple sequences together to form a single input data stream
(9) Stringbufferdinputstream (string input stream with cache)

3.OutputStream byte output stream

  • abstract class
  • Function: write data byte by byte to file or network
  • common method

(1) close() closes the output stream and frees the system resources associated with the stream
(2) flush() flushes this output stream and forces buffered byte data to be written to the target device
(3) write(byte []b) sends all the data of B to the output stream
Note: only write to the stream. To write to the target device, use flush()
(4) write(byte []b,int off,int len) writes len bytes from the specified byte array and outputs them to this output stream starting from offset off

  • Subclass

(1) Bytearrayoutputstream (byte array output stream)
(2) Fileoutputstream (file output stream)
The stream responsible for sequential output of local disk files
Construction method
Note: if there is such a file, it will be emptied; if there is no such file, it will be created
Create a File output stream and write the File represented by the specified File object (File file)
Create a file output stream and write the specified name. Writing a file (String name) overwrites the original content by default
(String name,boolean append)
true: do not overwrite the original content
false: overwrite the original content
(3) Filteroutputstream (filter output stream)
(4) Objectoutputstream (object output stream)
(5) Dataoutputstream (basic data type output stream)
(6) Pipedoutputstream

3. Character stream

1. Concept: read or write data from the stream in characters (16 bits), which is usually used to process character or string data

2.Reader character input stream

  • abstract class
  • Function: read data character by character into memory
  • common method

(1) close() closes the flow and releases all resources occupied by the flow
(2) read() reads a single character from the stream
(3) read(char []c) reads c.length character data from the current position and stores it in C
(4)(abstract)read(char []c,int off,int len)
Read the data of len characters from the current position, store and send it to c, and start writing from c[off] (byte [] B, int off, int len)

  • Subclass

(1) BufferedReader (reader with buffer) is efficient
(2)InputStreamReader
(3) FileReader convenience class
(4) Chararrayreader (character array Reader)
(5) Filterreader
(6) Pipedereader
(7) Stringreader (string Reader)

3.Writer character output stream

  • abstract class
  • Function: write data character by character to file or network
  • common method

(1) append() appends characters to this Writer stream and to the tail. Appends character sequences to this Writer stream and to the tail
Append the subsequence of the character sequence to the Writer stream. The subsequence is the start to end part of the sequence and appended to the tail
(2)close()
Close the flow and call flush() before closing
(3) flush() refreshes the stream and writes the data already in the stream to the specified target device
(4)write(char []c)
Writes a character array to the stream
(5) (abstract)write(char []c,int off,int len)
Writes the specified part of the character array to the stream, and writes len characters from off

  • Subclass

(1) Bufferedwriter (buffered Writer)
(2) OutputStreamWriter is a bridge between character flow and byte flow
(3) FileWriter convenience class
(4) Chararraywriter (character array Writer)
(5) Filterwriter
(6) Outputwriter (output stream Writer)
(7) Pipedwriter
(8) Printwriter
(9) Stringwriter (string Writer)

4. Mutual transformation

1.InputStream->Reader

  • InputStreamReader

2.OutputStream->Writer

  • OutputStreamWriter

5.ObjectIn/OutputStream

1. Serialization

  • Concept: convert objects into byte sequences

2. Deserialization

  • Concept: restore byte sequence to object

Should inherit Serializable

Posted by LordShryku on Fri, 10 Sep 2021 22:15:44 -0700