Java basic knowledge points (common classes, collections)

1. Commonly used classes

1. Comparator

Comparator and Comparable comparison:
1. Comparable is a sorting interface; if a class implements the Comparable interface, it means "the class supports sorting".
(Acts on the entity class)

2. Comparator is a comparator; if we need to control the order of a certain class, we can create a "comparator of this class" to sort.
(On the sorting class)

Summary: Comparable is equivalent to "internal comparator", and Comparator is equivalent to "external comparator".

2. Inner class

1. The member inner class is
defined in the class and serves as a member of the class.
Access authority: The inner class can access the properties and methods of the outer class. If the outer class wants to access the members of the inner class, it must first create an object of the inner class to access it.
Create an object: new Outer().new Inner()

2. The local inner class is
defined in the method and serves as a variable of the method. Note: The local inner class is like a local variable in the method. It cannot have public, protected, private and static modifiers.

3. Anonymous inner class
An anonymous inner class is usually used as a method to pass parameters. It is used to inherit abstract classes or implement interfaces, instead of subclasses or implementation classes, and does not require additional methods to be defined. Jdk8 can use Lambda expressions to simplify.

4. Static inner class A
static inner class can be understood as a static member of the class.
The static inner class does not need to depend on the object of the outer class, you can create your own object directly.
Cannot access the non-static member properties or methods of the external class. Because the static internal class does not depend on the external object, you can create the object by yourself. Therefore, if there is no external object, you can call the external instance member, which creates a contradiction, because the external instance member There must be external objects.

3. Packaging

The concept of packaging classes:
Since the basic data types do not have the concept of classes and objects, the design philosophy of Java is that everything is an object.
Therefore, a class of its own is specifically tailored for each basic data type, called a packaging class.

2. The application of packaging class.
Since the basic data types cannot be stored in the collection, the list.add(6) we have seen; in fact, the storage types are all packaging types. The process of upgrading from basic data types to packaging classes is called "boxing ", the opposite is called "unboxing";
1. Boxing-unboxing packaging class-basic data types are automatically carried out
2. Up
-casting-down-casting parent class-child class 3. Coercive type conversion-automatic conversion byte-short- int-long float-double

3. The construction method of
packaging class 1. All packaging classes can use the corresponding basic data types as parameters to construct their instances

2. In addition to the Character class, other packaging classes can use a string as a parameter to construct their instance

Note
1. When the parameter of the Boolean class construction method is String type, if the string content is true (regardless of case), the Boolean object represents true, otherwise it represents false

2. When the Number packaging class (except Character and Boolean other packaging classes) construction method parameter is String type, the string cannot be null, and the string must be parseable into the data of the corresponding basic data type, otherwise the compilation will not pass , NumberFormatException will be thrown at runtime

Summary:
1. The construction methods of packaging classes generally have overloads. The parameter of one construction method is the corresponding basic data type, and the parameter of the other construction method is the string type.

4. Commonly used methods of packaging classes
1.XXXValue(): packaging classes are converted to basic types (instance methods)
byteValue(), intValue(), longValue(), shortValue(), doubleValue(), floatValue()
charValue(), booleanValue()

2.toString(): returns the basic type data represented by the package object in the form of a string (basic type -> string)
(static method)
3. parseXXX(): converts the string to the corresponding basic data type data (except for Character ) (String -> basic type) (static method)

4. valueOf() (static method)
(1) All packaging classes have the following methods (basic type -> packaging class)
public static Type valueOf(type value)
(2) Except for the Character class, other packaging classes have the following methods (
String- >Packaging class) public static Type valueOf(String s)

4. String commonly used methods:

1. Length length();

2. Splicing str.concat(str2);

3. Format:
//Method 1
System.out.printf("Hello everyone, my name is %s, I am this year: %d years old, my deposit is: %f %n", "Cao Cao", 36,999.99);

//Method two
String s = String.format("Hello everyone, my name is %s, I am this year: %d years old, my deposit is: %f", "Cao Cao", 36,999.99);
System.out .println(s);

4.charAt(index) returns the character at the specified index

5.indexOf(str) returns the index of the first occurrence of the specified string in this string

6.compareTo(str2) compares two strings

7.equals()和equalsIgnoreCase()

8.getBytes() uses the default character set to turn the string into a byte array, which will be used in the IO stream

9.toCharArray() Convert a string to a character array

10. Interception: subString()

11. Convert to lower case toLowerCase() toUpperCase()

12. Blank trim() before and after interception

13. Replace: replace()

14. Split: split()

15.Regular match matches(String reg) returns boolean

5. Regular

1. Concept:
regular expression, also known as regular expression. (English: Regular Expression, often abbreviated as regex). Regular expressions are usually used to retrieve and replace text that meets a certain pattern (rule). Supports regular expressions: PHP, Java, Python, JavaScript, etc. With regular expressions, writing code is more concise, usually two or three lines of code can achieve the goal.

2. Rules:

  1. Any one character means to match any corresponding character, such as a matches a, 7 matches 7, and -matches.

  2. [] means matching any one of the characters in the brackets, such as [abc] matching a or b or c.

  3. -The meaning inside and outside the square brackets is different. For example, when it is outside, it will match -, if inside the square brackets [ab] means to match any of the 26 lowercase letters; [a-zA-Z] matches a total of 52 uppercase and lowercase letters Any of the letters; [0-9] matches any of the ten digits.

  4. The meaning inside and outside the square brackets is different. If it is outside, it means the beginning. For example, 7[0-9] means that the match starts with 7, and the second digit is a string of any number; if it is inside the square brackets, it means Any character other than this character (including numbers, special characters), such as [^abc] means to match any character other than abc.

  5. . Means to match any character.

  6. \d means number.

  7. \D means not a number.

  8. \w represents letters, numbers, and underscores, [a-zA-Z0-9_].

  9. \W means it is not composed of letters, numbers, and underscores.

  10. [\u4e00-\u9fa5] matches Chinese characters

  11. ?: Indicates 0 or 1 occurrence.

  12. + Means one or more occurrences.

  13. * Means 0, 1 or more occurrences.

  14. {n} means n occurrences.

  15. {n,m} means n~m occurrences.

  16. {n,} means that it appears n times or more.

3. Usage:
//The character to be matched
String str = "8";
//Regular expression
String regex = "[0-9]";
//
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
System.out.println(m.matches());
//Method two
System.out.println(Pattern.matches(regex, str));
//Method three
System.out.println( str.matches(regex));

Extension: Assert, predict, exclude
//A certain website requires the registration of the account only: letters and numbers, not both letters, not both numbers, and require the beginning of a letter, the length is between 6-12,
public static void main (String[] args) { Scanner sc=new Scanner(System.in); //Assertion, prediction (?! Regular) Exclude regular matching String s=""; while (!s.matches(" 1 (? ![a-zA-Z]{5,11}$)[a-zA-Z0-9]{5,11}")){ System.out.println("Please enter the registered account number:"); s = sc.next(); } System.out.println("Registered successfully!"); }








6.StringBuffer和StringBuild

1. Difference:
StringBuffer is safer and
StringBuilder is faster

Inheritance structure diagram:
Insert picture description here

2. The same
StringBuffer and StringBuilder usage are the same

3. Common methods
//1.
append()

//2. Insert
insert()

//3. Invert
reverse()

7. Math and Random

1. Common methods of Math
: round up/down, round up ceil() floor() round()

Absolute value abs()

Random number random() Range: [0,1) decimal

Power function pow(a,b)

sqrt() square root

2. Random common methods
Insert picture description here

Insert picture description here

8. Date class

1.Date

1. Create a Date object of the current time
//Create a Date object representing the current date of the system
Date d = new Date();

2. Create a Date object of the time we specify:
Use the parameterized construction method Date(int year, int month, int day) to construct the Date class object of the specified date. The year parameter in the Date class should be the actual need to represent 1900 is subtracted from the year, and the value after 1 is subtracted from the actual month represented.

//Create a Date object representing June 12, 2014
Date d1 = new Date(2014-1900, 6-1, 12); (note the parameter settings)

3. Obtain the information contained in a date object correctly, such as:
Date d2 = new Date(2014-1900, 6-1, 12);
//Get the year (note that the year must be added to 1900, so that it is the date object d2 Represented year)
int year = d2.getYear() + 1900;
//Get the month (note that the month must be added by 1, so that it is the month represented by the date object d2)
int month = d2.getMonth() + 1;
// Get the date
int date = d2.getDate();
//get the hour
int hour = d2.getHours();//do not set the default to 0
//get the minute
int minute = d2.getMinutes();
//get the second
int second = d2.getSeconds();
//Get the day of the week
int day = d2.getDay();
No data in the construction method will default to the current time.

2.Calendar

1. The function of the Calendar class is much stronger than that of the Date class, taking into account issues such as time zone.

2. The Calendar class is an abstract class that provides the getInstance method to create objects.

//1. Create a Calendar object representing the current date of the system
Calendar c = Calendar.getInstance();//The default is the current date

//2. Create a Calendar object
Calendar c1 = Calendar.getInstance();
c1.set(2014, 5-1, 9);

//3. Create a Calendar object with a specified date-Method two
c1.set(Calendar.DATE,10);
c1.set(Calendar.YEAR,2015);

//4. Get the time

// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;(MONTH+1)
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几
int day = c1.get(Calendar.DAY_OF_WEEK);

//5. Associated with Date

setTime(new Date())

3.SimpleDateFormat

//1. Create a formatting object
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//2. Call the format or parse method to convert between String and Date

9. Numbers

1.BigDecimal

Common methods:

//
Add the values ​​in the BigDecimal object and return the BigDecimal object add(BigDecimal)

//Subtract the value in the BigDecimal object and return the BigDecimal object
subtract(BigDecimal)

//Multiply the values ​​in the BigDecimal object and return the BigDecimal object
multiply(BigDecimal)

//Divide the value in the BigDecimal object, and return the BigDecimal object
divide(BigDecimal)

BigDecimal b1 = new BigDecimal(“0.03”);
BigDecimal b2 = new BigDecimal(“0.02”);
System.out.println(b1.subtract(b2));

//Compare the output result
BigDecimal b1 = new BigDecimal(0.03);
BigDecimal b2 = new BigDecimal(0.02);
System.out.println(b1.subtract(b2));

2. Biginteger
If the operation of an integer has exceeded the range of long, BigInteger can be used at this time. Since it is not a basic data type, ±*/ cannot be used, and the operation method is the same as above.

long l = 999999999999999999l;

BigInteger in1=new
BigInteger(“999999999999999999999999999999999999999999”);

BigInteger in2=new
BigInteger(“999999999999999999999999999999999999999998”);

System.out.println(in1.subtract(in2));

Conversion between decimal and binary

BigInteger in = new BigInteger(“10001110”,2);

System.out.println(in.intValue());//Binary is converted to decimal

System.out.println(in.toString(2));//Decimal conversion to

System.out.println(in.toString(3));

3. DecimalFormat
double pi = 3.1415927;//Pi
//Take an integer
System.out.println(new DecimalFormat("0").format(pi));//3

//Take one integer and two decimals
System.out.println(new DecimalFormat("0.00").format(pi));//3.14

//Take two integers and three decimal places, and the insufficient part of the integer is filled with 0.
System.out.println(new DecimalFormat("00.000").format(pi));// 03.142

//Take all integer parts
System.out.println(new DecimalFormat("#").format(pi));//3

//Count in percentage and take two decimal places
System.out.println(new DecimalFormat("#.##%").format(pi));//314.16%

long c =299792458;//speed of light

//Display in scientific notation, and take five decimal places
System.out.println(new DecimalFormat("#.#####E0").format©);//2.99792E8

//Display as a two-digit integer scientific notation, and take four decimal places
System.out.println(new DecimalFormat("00.####E0").format©);//29.9792E7

//Every three digits are separated by commas.
System.out.println(new DecimalFormat(",###").format©);//299,792,458

// Embed the format into the text
System.out.println(new DecimalFormat("The speed of light is per second, ###meters.").format©);

Second, the collection framework

1. Container:

variable

Array features: fixed type, fixed length

The characteristics of the class: different types of member attributes, which together describe an entity class

Collection characteristics: the type is not fixed, the length is not fixed, and any data is stored at will

2. Recognize the inheritance structure of the collection framework:

Insert picture description here

3.ArrayList

The collection has no fixed length:
Insert picture description here

Common method

Insert picture description here
Insert picture description here

4.LinkedList

The storage principle is a linked list. There are a pre-node and a post-node before and after the element, which are used to connect the previous element and the next element in the set, and then "hand in hand" to form a set of chained data. .

Unique method
Insert picture description here

5. Comparison of two List collections

1. The List interface stores a set of objects that are not unique (can be repeated) and ordered (insertion order)

2. ArrayList implements a variable-length Object type array, allocates continuous space in memory, and traverses elements and randomly accesses elements more efficiently

3. LinkedList adopts linked list storage method, which is more efficient when inserting and deleting elements

4. Compare the difference between the two structures by viewing the source code of the adding method. Chain storage and array storage

Insert picture description here

The reason for the different efficiency:
Linkedlist will only affect the two adjacent elements when deleting and adding operations.

Since Arraylist is an array in nature, the address values ​​of all subsequent elements will be shifted when performing delete and add operations.

6.Set collection

1. Se interface features:

Store a set of unique (duplicate elements are not allowed), unordered (no index subscript) objects, HashSet is a commonly used implementation class of the Set interface.

2. Manipulate the data of the Set collection

(1) New elements

(2) Delete elements

3. Traverse the Set collection
1. Enhance the for
2. Iterator (fixed with the while loop)

7.Map collection

1. The Map interface specializes in processing key-value mapping data, and can realize the operation of the value according to the key

2. Create a HashMap object that is commonly used to implement the Map interface and store it in the data

3. Delete data

4. Modify the data

5. Traverse the data of the map collection:

1. Traverse all keys
2. Traverse all values
3. Traverse all key-value pairs

Summary of commonly used methods:

Insert picture description here

to sum up

The above is all the knowledge points of commonly used classes and collections, mainly related concepts and usage methods of commonly used classes and collections.


  1. a-zA-Z ↩︎

Guess you like

Origin blog.csdn.net/StruggleBamboo/article/details/111699351