20165318 2017-2018-2 "Java Program design" Sixth week study summary teaching Contents study Summary Eighth chapter common practical Class 1, String class
- The string class is used to process character sequences, and in the Java.lang package, the program can use the string class directly. It is important to note that Java declares the string class as the final class, so the user cannot extend the string class, that is, the string class may not have subclasses.
constant Object : A string constant object is a sequence of characters enclosed in double quotation marks, for example: "Hello", "12.97", "Boy", and so on. String constants are placed in a constant pool.
String Object : You can use the string class to declare an object and create an object, for example:
String s = new String("we are students");
Note : Users cannot output a reference to a string object:
Syste.out.println(s);
The output is the entity of the object.
The two more common construction methods of string
-
String (char a[])Creates a string object with a character array A.
-
String(char a[],int startIndex,int count)Extracts a subset of the characters in array A to create a string object, with the arguments startindex and count specifying the starting position of the extracted character in A and the number of characters that were intercepted from that position.
The string is collocated
A string object can be collocated with "+", that is, a new string object is obtained from the end-to-end phase.
-
If the two constants are collocated, the resulting constants are still constant, and if the constant pool does not have this constant, it is placed in the constant pool.
-
The string object that participates in the collocated operation, as long as one is a variable, then Java holds the entity and reference of the resulting new string object in the dynamic zone.
Common methods of the string class
- public int Length (): Gets the length of a string
-
public boolean equals (String s): Determines whether the character sequence of the current string object is the same as the character sequence of the string object specified by the parameter s
-
public Boolean startsWith (String s):
Determines whether the character sequence prefix of the current string object is the character sequence of the string object s specified by the argument
-
public Boolean endsWith (String s):
Determines whether the character sequence suffix of the current string object is the character sequence of the string object s specified by the argument
-
public int CompareTo (String s): Compares the size of the character sequence specified by the dictionary order with the parameter S.
-
Public Boolean contains (string s): The string object calls the Contains method to determine whether the character sequence of the current String object contains the character sequence of the parameter s
-
public int indexOf (String str): The string object invokes the method to retrieve the position of the first occurrence of the character sequence of STR, starting at the 0 index position of the character sequence of the current String object, and returns the position. If not retrieved, the value returned by the method is –1.
-
public int lastIndexOf (String s): Retrieves the position of the last occurrence of the character sequence of STR, starting at the 0 index position of the character sequence of the current String object, and returns the position. If not retrieved, the value returned by the method is-1.
-
public string substring (int startpoint): The string object calls the method to get a new string object, The character sequence of the new string object is the sequence of characters that is obtained by copying the startpoint position to the last position in the character sequence of the current string object. The string object calls the substring (int start, int end) method to get a new string object, and the character sequence of the new string object is to copy the start position in the character sequence of the current string object to end– The character sequence that is obtained by the characters on the 1 position.
-
public string trim (): Gets a new string object that is a sequence of characters after the character sequence of the current string object is removed from the front and back spaces.
Conversion of strings to basic data
The integer class in the Java.lang package calls its class method:
public static int parseInt(String s)A string consisting of "number" characters can be set.
public static byte parseByte(String s) throws NumberFormatException
public static short parseShort(String s) throws NumberFormatException
public static long parseLong(String s) throws NumberFormatException
public static float parseFloat(String s) throws NumberFormatException
public static double parseDouble(String s) throws NumberFormatException
You can use the class method of the string class to convert a numeric value to a String object:
public static String valueOf(byte n)
public static String valueOf(int n)
public static String valueOf(long n)
public static String valueOf(float n)
public static String valueOf(double n)
The string representation of the object
The object class has apublic String toString()
method, an object can get the character sequence representation of the object by calling the method. An object calls the ToString () method to return the general form of the character sequence of a string object:
String name representation of the name of the class that created the object
string and character array
-
How to construct the String class:
String(char[]);
String(char[],int offset,int length): Creates a string object with all and part of characters in a character array, respectively
-
The method of storing a string object's sequence of characters into an array:
public void getChars(int start,int end,char c[],int offset ): the partial character sequence of a string object is stored in the array.
public char[] toCharArray(): stores all the character sequences of a string object into an array.
string and byte array
-
Construction method
String(byte[]): Constructs a string object with the specified byte array.
String(byte[],int offset,int length): Constructs a string object using the specified byte array, starting at offset from the beginning of the array, and taking a length byte.
-
Related methods:
public byte[] getBytes(): Stores the character sequence of the current string object into a byte array using the platform's default character encoding, and returns a reference to the array.
public byte[] getBytes(String charsetName): Specifies a character encoding using a parameter, stores the character sequence of the current string object into a byte array, and returns a reference to the array.
Regular expressions
-
A regular expression is a sequence of characters of a string object that contains special-meaning characters that are called metacharacters in regular expressions.
-
The string object invokes thepublic boolean matches(String regex)method to determine whether the character sequence of the current string object matches the regular expression specified by the parameter regex.
2, StringTokenizer class
To decompose the character sequence of a string object using the StringTokenizer object
Two common methods of construction :
-
StringTokenizer(String s): Constructs a parser for string object s, using the default delimited tags, which are space characters, line breaks, carriage returns, tab characters, and paper feed characters for split marks
-
StringTokenizer(Strings,String delim): Constructs a parser for string object s, and any permutation of characters in the character sequence of the parameter Delim is used as a delimited marker
The StringTokenizer object, called a string parser, can use the following methods :
-
nextToken(): Gets the language symbol (word) in the string one at a, and the value of the variable responsible for the count in the string parser is automatically reduced.
-
hasMoreTokens(): If there is a language symbol in the string, that is, the value of the count variable is greater than 0, the method returns True, otherwise false is returned.
-
countTokens(): Gets the value of the count variable in the parser
3, Scanner class
Use the scanner class to parse the data that the program needs from the string.
Scanner Objects : You can parse words in a sequence of characters
scanner The space as a delimited tag to parse the word in the sequence of characters, specifically parsing the operation :
-
The Sanner object calls the next () method to return the word in the parsed sequence of characters, and if the last word has been returned by the next () method, the Scanner object call Hasnext () returns false, otherwise ture
-
For a numeric word in a parsed sequence of characters, the scanner object can replace the next () method with the Nextint () or nextdouble () method
-
If the word is not a numeric word, the scanner object calls the Nextint () or nextdouble () method to convert a numeric word to int or double data to return
-
If the word is not a numeric word, the scanner object calls the Nextint () or nextdouble () method to have a inputmismatchexception exception, and the next () method can be called to return a non-digitized word when handling an exception.
parsing strings using regular expressions as delimited tokens
The scanner object can call Usedelimiter (regular expression); The method takes a regular expression as a delimited token, that is, the string that matches the regular expression is a delimited tag.
4, StringBuffer class
three methods of construction :
- StringBuffer ()
- StringBuffer (int size)
- StringBuffer (String s)
common methods of the StringBuffer class :
StringBuffer append(String s): Appends the character sequence of the string object s to the character sequence of the current StringBuffer object and returns a reference to the current StringBuffer object
StringBuffer append(int n): Converts the int data n to a string object, appends the string object's character sequence to the current StringBuffer object's character sequence, and returns a reference to the current StringBuffer object
StringBuffer append(Object o): Appends a sequence of characters for an Object object o to the character sequence of the current String-buffer object and returns a reference to the current StringBuffer object
- Public chat charAt (int n) and public void Setcharat (int n, char ch)
public chat charAt(int n ): Gets the single character of the set specified by the parameter n
public void setCharAt(int n ,char ch): Replaces the character at the string position n in the current StringBuffer object entity with the character specified by the parameter ch
-
StringBuffer insert(int index, String str): Inserts the string specified by the parameter str into the position specified by the parameter index
-
public StringBuffer reverse(): Flips the characters in the object entity
-
StringBuffer delete(int startIndex, int endIndex): Removes a substring from a string in the current StringBuffer object entity
-
StringBuffer replace(int startIndex,int endIndex,String str): Replaces a substring of a string in the current StringBuffer object entity with a string specified by the parameter str
5. Date and Calendar class
Date class
-
The date class is constructed by using the date () object created with the parameterless construction method of the date class to get the local current time
-
Construction method of the date class two: date (long time) using the long parameter to create the specified times
The computer system sets the "ad" of its own time on January 1, 1970 0 o'clock (Greenwich Mean Time), which can be used to construct a date object by using the date's parameterized construction method: Date (long time).
Calendar class
-
Use the static method of the Calendar class getinstance () to initialize a calendar object.
-
The Calendar object can call methods:
public final void set(int year,int month,int date)
public final void set(int year,int month,int date,int hour,int minute)
public final void set(int year,int month, int date, int hour, int minute,int second)
Its role is to turn the calendar to any one time.
6. Math, BigInteger, and random classes
Math class
-
The math class is in the Java.lang package. The math class contains a number of class methods for scientific computation that can be called directly from the class name. In addition, the math class has two static constants, each of which are:
E 2.7182828284590452354andPI 3.14159265358979323846.
-
Common class methods for the math class:
public static long abs(double a)Returns the absolute value of a.
public static double max(double a,double b)Returns the maximum value of a, B.
public static double random()Generates a random number from 0 to 1 (excluding 0 and 1).
public static double pow(double a,double b)Returns a power of B.
public static double sqrt(double a)Returns the square root of a.
public static double log(double a)Returns the logarithm of a.
public static double sin(double a)Returns the sine value.
public static double asin(double a)Returns the inverse sine value.
BigInteger class
-
The BigInteger class in the Java.math package provides integer operations of arbitrary precision. You can use the construction method:
public BigInteger(String val)Constructs a decimal BigInteger object.
-
Common class methods for the BigInteger class:
public BigInteger add(BigInteger val)Returns the and of the large integer object specified by the current large integer object with the parameter.
public BigInteger subtract(BigInteger val)Returns the difference between the current large integer object and the large integer object specified by the parameter.
public BigInteger multiply(BigInteger val)Returns the product of the large integer object specified by the current large integer object with the parameter.
public BigInteger divide(BigInteger val)Returns the quotient of the current large integer object with the large integer object specified by the parameter.
public BigInteger remainder(BigInteger val)Returns the remainder of the large integer object specified by the current large integer object with the parameter.
public int compareTo(BigInteger val)Returns the result of a comparison of the current large integer object with the large integer specified by the parameter, which is 1,-1, or 0, representing the large integer that the current large integer object is greater than, less than, or equal to the specified parameter.
public BigInteger pow(int a)Returns a power to the current large integer object.
public String toString()Returns a string representation of the current large integer object in decimal.
public String toString(int p)Returns a string representation of the current large integer object P-binary.
Random class
Used to get random numbers
- The following construction method is used for the random class:
public Random();
public Random(long seed); Create a random object with the seed specified by the parameter seek
15th. Generics and set frame 1, generic type
Generics (generics), the main purpose is to establish a type-safe collection framework, such as linked lists, hash maps and other data structures.
Declaration of a generic class
- You can use the class name <generic list> to declare a class. In order to distinguish it from ordinary classes, such declared classes are called generic classes, such as:
class People
Declaring an object using a generic class
-
When a generic class declares and creates an object, the class name is followed by a pair of "<>", and you must replace the generics in "<>" with a specific type. For example:
Cone<Circle> coneOne; coneOne =new Cone<Circle>(new Circle());
2. Linked list
A linked list is a data structure consisting of several objects called nodes, each of which contains a reference to the next node.
LinkedList
LinkedList<String> mylist=new LinkedList<String>();Create an empty doubly linked list.
add(E obj)Adds nodes to the linked list in turn.
LinkedList
-
public boolean add(E element)Adds a new node to the end of the list that is the data specified by the parameter elememt.
-
public void add(int index ,E element)Adds a new node to the list at the specified location, and the data in that node is the data specified by the parameter elememt.
-
public void clear()Deletes all nodes of the linked list, making the current list an empty list.
-
public E remove(int index)Deletes the node at the specified location.
-
public boolean remove(E element)Removes the first occurrence of a node that contains data elemen.
-
public E get(int index)Gets the data in the node at the specified position in the linked list.
LinkedList
-
public void addFirst(E element)Adds a new node to the head of the linked list, which is the data specified by the parameter elememt.
-
public void addLast(E element)Adds a new node to the end of the list that is the data specified by the parameter elememt.
-
public E getFirst()Gets the data from the first node in the linked list.
-
public E getLast()Gets the data from the last node in the linked list.
-
public E removeFirst()Deletes the first node and returns the data in that node.
Collections Class
The class methods provided by the collections class for sorting and finding are as follows:
-
public static sort(List<E> list)The method can arrange the elements in the list in ascending order.
-
int binarySearch(List<T> list, T key,CompareTo<T> c)Use the binary method to find if the list contains an element equal to the parameter key, and if an element in the key list is equal, the method returns the index position of the element in the linked list (the index position of the linked list from the 0 exam), otherwise returns-1.
-
public static void shuffle(List<E> list)The data in list is re-arranged randomly by shuffling algorithm.
-
static void rotate(List<E> list, int distance)Rotates the data in the linked list.
-
public static void reverse(List<E> list)Flipping data in a list
3. Stack
A stack is a "last-in, first-out" data structure that can only be used to enter or output data at one end.
Stack:
-
public E push(E item): Push stack operation is achieved
-
public E pop(): Implements the stack operation.
-
public boolean empty(): Determines whether the stack has data.
-
public E peek(): Gets the data at the top of the stack, but does not delete the data.
-
public int search(Object data): Gets the position of the data in the stack
4. Hash map
HashMap
HashMap
Common methods
-
public void clear()Empties the hash map.
-
public Object clone()Returns a clone of the current hash map.
-
public boolean containsKey(Object key)The method returns true if the hash map has a key/value pair with the key specified by the parameter, otherwise false is returned.
-
public boolean containsValue(Object value)If the hash map has a value for the "key/value" pair, the value specified by the parameter is.
-
public V get(Object key)Returns the value of the key/value pair in the hash map using key.
-
public boolean isEmpty()If the hash map does not contain any "key/value" pairs, the method returns True, otherwise false is returned.
-
public V remove(Object key)Removes the key/value pair specified by the key parameter in the hash map, and returns the value corresponding to the key.
-
public int size()Returns the size of the hash map, which is the number of "key/value" pairs in the hash map.
Traverse Hash Map
public Collection<V> values()method returns an implementation collection
5. Tree Set
TreeSet: TreeSet
Common methods of TreeSet class
-
public boolean add(E o)Adds nodes to the tree set.
-
public void clear()Deletes all nodes in the tree set.
-
public void contains(Object o)The method returns true if there is an object specified by the containing parameter in the tree set, otherwise false is returned.
-
public E first()Returns the data from the first node in the tree set (the smallest node).
-
public E last()Returns the data from the last node (the largest node).
-
public isEmpty()Determines whether it is an empty tree set, and returns True if the tree set does not contain any nodes.
-
public boolean remove(Object o)Deletes the smallest node of the object specified by the storage parameter in the tree set.
-
public int size()Returning nodes in a tree set
6. Tree Mapping
Problems in code debugging and the resolution process
-
Issue 1: When compiling run example8_7, there is a problem in running the result, as follows
-
Resolution process: Carefully check the code, found that no problem writing, see the results of the run, the results show that the string length is 10, and GB2312 encoded 8 different, I guess it is UTF-8 in the byte length and GB2312 different, I calculated UTF-8 Chinese characters byte length is 3, After this correction code, it can be run normally. The result of the operation is as follows: It can be concluded that the byte length ofChinese characters in GB2312 is 3 in 2,utf-8.
-
Issue 2: Example15_8 when compiling: Exception in thread "main" java.lang.NoSuchMethodError:Student.
-
Resolution: Prompt class with the same name in the same package or project, change Example15_8 and Example15_9 in the same name of the student class, and save, it can run normally.
Code Cloud Link:
Https://gitee.com/besti-is-java-2018/20165318_sun_xiaoxuan
Code hosting:
20165318 2017-2018-2 "Java Programming" Sixth Week study summary