1, String related classes
1. String class and common methods
String: a string, represented by a pair of "".
① String is declared as final and cannot be inherited.
② String implements the Serializable interface: it means that the string supports serialization.
String implements the Comparable interface: it means that string can compare sizes.
③ final char[] value is defined inside String to store String data.
④ String represents an immutable character sequence. Abbreviation: non variability.
reflect:
a. When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
b. When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
c. When you call the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.
⑤ Assign a value to a string by literal means (different from new). At this time, the string value is declared in the string constant pool.
⑥ Strings with the same content will not be stored in the string constant pool.
@Test public void test1(){ String s1 = "abc";//Definition of literal quantity String s2 = "abc"; s1 = "hello"; System.out.println(s1 == s2);//Compare the address values of s1 and s2 System.out.println(s1);//hello System.out.println(s2);//abc System.out.println("*****************"); String s3 = "abc"; s3 += "def"; System.out.println(s3);//abcdef System.out.println(s2); System.out.println("*****************"); String s4 = "abc"; String s5 = s4.replace('a', 'm'); System.out.println(s4);//abc System.out.println(s5);//mbc }
Instantiation method of String:
① By literal definition
② Through the new + constructor
Note 1: String s = new String("abc"); How many objects are created in memory?
Two. One is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc"
@Test public void test2(){ //Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area. String s1 = "javaEE"; String s2 = "javaEE"; //Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space. String s3 = new String("javaEE"); String s4 = new String("javaEE"); System.out.println(s1 == s2);//true System.out.println(s1 == s3);//false System.out.println(s1 == s4);//false System.out.println(s3 == s4);//false System.out.println("***********************"); Person p1 = new Person("Tom",12); Person p2 = new Person("Tom",12); System.out.println(p1.name.equals(p2.name));//true System.out.println(p1.name == p2.name);//true p1.name = "Jerry"; System.out.println(p2.name);//Tom }
Note 2:
Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area.
String s1 = "javaEE";
String s2 = "javaEE";
Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space.
String s3 = new String("javaEE");
String s4 = new String("javaEE");
Supplement:
@Test public void test3(){ String s1 = "javaEE"; String s2 = "hadoop"; String s3 = "javaEEhadoop"; String s4 = "javaEE" + "hadoop"; String s5 = s1 + "hadoop"; String s6 = "javaEE" + s2; String s7 = s1 + s2; System.out.println(s3 == s4);//true System.out.println(s3 == s5);//false System.out.println(s3 == s6);//false System.out.println(s3 == s7);//false System.out.println(s5 == s6);//false System.out.println(s5 == s7);//false System.out.println(s6 == s7);//false String s8 = s6.intern();//Return the "Java EE Hadoop" that already exists in the constant value used by s8 System.out.println(s3 == s8);//true }
① The splicing result of constants and constants is in the constant pool. And constants with the same content will not exist in the constant pool.
② As long as one of them is a variable, the result is in the heap.
③ If the result of splicing calls the intern() method, the return value is in the constant pool.
Common methods of String class:
int length(): returns the length of the string: return value length
char charAt(int index): returns the character at an index: return vlaue[index]
boolean isEmpty(): judge whether it is an empty string: return value length == 0
String toLowerCase(): converts all characters in a string to lowercase using the default locale
String toUpperCase(): converts all characters in a string to uppercase using the default locale
String trim(): returns a copy of a string, ignoring leading and trailing whitespace
boolean equals(Object obj): compare whether the contents of strings are the same
Boolean equalsignorecase (string otherstring): similar to the equals method, case is ignored
String concat(String str): connects the specified string to the end of this string. Equivalent to "+"
Int CompareTo (string otherstring): compare the size of two strings
String substring(int beginIndex): returns a new string, which is the last substring of the string intercepted from beginIndex
String substring(int beginIndex,int endIndex): returns a new string, which is a substring intercepted from beginIndex to endindex (excluding)
boolean endsWith(String suffix): test whether the string ends with the specified suffix
boolean startsWith(String prefix): test whether this string starts with the specified prefix
Boolean startswith (string prefix, int tofffset): test whether the substring of this string starting from the specified index starts with the specified prefix
Boolean contains (charsequences): returns true if and only if this string contains the specified char value sequence
int indexOf(String str): returns the index of the first occurrence of the specified substring in this string
int indexOf(String str,int fromIndex): returns the index of the first occurrence of the specified substring in this string, starting from the specified index
int lastIndexOf(String str): returns the index of the rightmost occurrence of the specified substring in this string
int lastIndexOf(String str,int fromIndex): returns the index of the last occurrence of the specified substring in the string, and searches reversely from the specified index
String replace(char oldChar,char newChar): returns a new string obtained by replacing all oldchars appearing in this string with newChar
String replace(CharSequence target,CharSequence replacement): replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence
String replaceAll(String regex,String replacement): replace all substrings of this string that match the given regular expression with the given replacement
String replaceFirst(String regex,String replacement): replace this string with the given replacement to match the first substring of the given regular expression.
boolean matches(String regex): tells whether the string matches the given regular expression
String[] split(String regex): splits the string according to the matching of the given regular expression
String[] split(String regex,int limit): split the string according to the matching given regular expression. The maximum number is no more than limit. If it exceeds the limit, all the rest will be put into the last element
@Test public void test4(){ String str1 = "Beijing Shang Silicon Valley Education Beijing"; String str2 = str1.replace('north', 'east'); System.out.println(str1); System.out.println(str2); String str3 = str1.replace("Beijing", "Shanghai"); System.out.println(str3); System.out.println("*************************"); String str = "12hello34world5java7891mysql456"; //Replace the number in the string with,, and remove it if there are at the beginning and end of the result String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", ""); System.out.println(string); System.out.println("*************************"); str = "12345"; //Judge whether all str strings are composed of numbers, i.e. 1-n numbers boolean matches = str.matches("\\d+"); System.out.println(matches); String tel = "0571-4534289"; //Judge whether this is a fixed line telephone in Hangzhou boolean result = tel.matches("0571-\\d{7,8}"); System.out.println(result); System.out.println("*************************"); str = "hello|world|java"; String[] strs = str.split("\\|"); for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); } System.out.println(); str2 = "hello.world.java"; String[] strs2 = str2.split("\\."); for (int i = 0; i < strs2.length; i++) { System.out.println(strs2[i]); } }
Note 1: indexOf and lastIndexOf methods return - 1 if they are not found
Note 2: under what circumstances do indexOf(str) and lastIndexOf(str) return the same value?
Case 1: there is a unique str. Case 2: STR does not exist.
2,StringBuffer,StringBuilder
What are the similarities and differences among String, StringBuffer and StringBuilder?
① String: immutable character sequence; The bottom layer uses char [] storage
② StringBuffer: variable character sequence; Thread safe and inefficient; The bottom layer uses char [] storage
③ StringBuilder: variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage
Source code analysis:
String str = new String(); //char[] value = new char[0];
String str1 = new String("abc"); //char[] value = new char[]{'a','b','c'};
StringBuffer sb1 = new StringBuffer();
//char[] value = new char[16]; The bottom layer creates an array with a length of 16
System.out.println(sb1.length()); //0
sb1.append('a'); //value[0] = 'a';
sb1.append('b'); //value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char["abc".length() + 16];
System.out.println(sb2.length()); //3
Note: capacity expansion
If the data to be added cannot be contained in the underlying array. Then you need to expand the underlying array.
By default, the capacity expansion is 2 times + 2 of the original capacity, and the elements in the original array are copied to the new array.
It is recommended to use StringBuffer(int capacity) or StringBuilder(int capacity) in development
Common methods of StringBuffer:
StringBuffer append(xxx): provides many append() methods for string splicing
StringBuffer delete(int start,int end): deletes the contents of the specified location
StringBuffer replace(int start,int end,String str): replace the [start,end] position with str
StringBuffer insert(int offset,xxx): insert xxx at the specified position
StringBuffer reverse(): reverses the current character sequence
public int indexOf(String str): returns the index of the first occurrence of the specified substring in this string
public String substring(int start,int end): returns a substring of the left closed right open interval from start to end
public int length(): returns the length of the string
public char charAt(int index): returns the character at an index
public void setCharAt(int index,char ch): sets the character at an index to the specified character
Supplement 1: efficiency of String, StringBuffer and StringBuilder:
Arrange from high to low: StringBuilder > StringBuffer > String
Supplement 2: conversion between String, StringBuffer and StringBuilder
String -- > StringBuffer, StringBuilder: call the constructor of StringBuffer and StringBuilder
StringBuffer,StringBuilder ---> String:
① Call the constructor of String ② call StringBuffer and toString of StringBuilder
Supplement 3: conversion between String class and other structures
① Conversion between String, basic data type and wrapper class
String -- > basic data type, wrapper class: call the static method of wrapper class: parseXxx(str)
Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String
@Test public void test1(){ String str1 = "123"; int num = Integer.parseInt(str1); String str2 = String.valueOf(num);//"123" String str3 = num + ""; System.out.println(str1 == str3); }
② Conversion between String and char []
String -- > char []: call toCharArray() of string
char [] --- > String: call the constructor of String
@Test public void test2(){ String str1 = "abc123"; char[] charArray = str1.toCharArray(); for (int i = 0; i < charArray.length; i++) { System.out.println(charArray[i]); } char[] arr = new char[]{'h','e','l','l','o'}; String str2 = new String(arr); System.out.println(str2); }
③ Conversion between String and byte []
Code: String -- > byte []: call getBytes() of string
Decoding: byte [] --- > String: call the constructor of String
Encoding: String -- > bytes (binary data that can be understood -- > but cannot be understood)
Decoding: inverse process of encoding, byte -- > string (incomprehensible binary data -- > understandable)
@Test public void test3() throws UnsupportedEncodingException { String str1 = "abc123 China"; byte[] bytes = str1.getBytes();//Use the default character set for encoding. System.out.println(Arrays.toString(bytes));//[97, 98, 99, 49, 50, 51, -28, -72, -83, -27, -101, -67] byte[] gbks = str1.getBytes("gbk");//Use gbk character set for encoding. System.out.println(Arrays.toString(gbks));//[97, 98, 99, 49, 50, 51, -42, -48, -71, -6] System.out.println("******************"); String str2 = new String(bytes);//Decode using the default character set. System.out.println(str2);//abc123 String str3 = new String(gbks); System.out.println(str3);//Garbled code. Cause: the encoding set and decoding set are inconsistent! String str4 = new String(gbks, "gbk");//Decode using the specified character set. System.out.println(str4);//There is no garbled code. Reason: the encoding set and decoding set are consistent! }
Note: when decoding, it is required that the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear.
2, Date time API before JDK 8
1. System static method
currentTimeMillis() in System class: returns the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970, which is called timestamp.
@Test public void test1(){ long time = System.currentTimeMillis(); System.out.println(time);//1643550893142 }
2. Date class
java.util.Date class (parent class)
> java. sql. Date class (subclass)
① Use of two constructors
>Constructor 1: Date() --- > create a Date object corresponding to the current time: Date date1 = new Date();
>Constructor 2: create a Date object with a specified number of milliseconds: Date date2 = new Date(155030620410L);
② Use of two methods
>Tostring(): displays the current year, month, day, hour, minute and second
>Gettime(): get the number of milliseconds (timestamp) corresponding to the current Date object
③java.sql.Date corresponds to a variable of date type in the database
>How to instantiate: Java sql. Date date3 = new java. sql. Date(35235325345L);
>How to convert Java util. Date object is converted to Java sql. Date object:
//Case 1:
Date date4 = new java.sql.Date(2343243242323L);// polymorphic
java.sql.Date date5 = (java.sql.Date) date4;// Downward transformation
//Case 2:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
@Test public void test2(){ //Constructor 1: Date(): creates a Date object corresponding to the current time Date date1 = new Date(); System.out.println(date1.toString());//Sat Feb 16 16:35:31 GMT+08:00 2019 System.out.println(date1.getTime());//1550306204104 //Constructor 2: create a Date object with a specified number of milliseconds Date date2 = new Date(155030620410L); System.out.println(date2.toString()); //Create Java sql. Date object java.sql.Date date3 = new java.sql.Date(35235325345L); System.out.println(date3);//1971-02-13 //How to convert Java util. Date object is converted to Java sql. Date object //Case 1: // Date date4 = new java.sql.Date(2343243242323L);// polymorphic // java.sql.Date date5 = (java.sql.Date) date4;// Downward transformation //Case 2: Date date6 = new Date(); java.sql.Date date7 = new java.sql.Date(date6.getTime()); }
3. Calendar Class (abstract class)
① Instantiation
Method 1: create an object of its subclass (Gregorian calendar)
Method 2: call its static method getinstance() --- > common
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass());
② Common methods (calendar variability)
get():
int days = calender.get(Calender.DAY_OF_MONTH);
set():
calendar.set(Calendar.DAY_OF_MONTH,22);
days = calendar.get(Calendar.DAY_OF_MONTH);
add():
calendar.add(Calendar.DAY_OF_MONTH,-3);
days = calendar.get(Calendar.DAY_OF_MONTH);
getTime(): Calendar Class -- > date()
Date date = calendar.getTime();
setTime(): date -- > Calendar Class
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
4. SimpleDateFormat class:
① SimpleDateFormat formatting and parsing of Date class
Format: date -- > string: call the format method of sdf
Date date = new Date();
System.out.println(date);//Sun Jan 30 22:26:22 CST 2022
String format = sdf.format(date);
System.out.println(format);//22-1-30 10:26 PM
Parsing: inverse process of formatting, string -- > date: call the parse method of sdf
String str = "19-12-18 11:43 am";
Date date1 = sdf.parse(str);
System.out.println(date1);//Wed Dec 18 11:43:00 CST 2019
② Instantiation of SimpleDateFormat
① Use the default constructor: SimpleDateFormat sdf = new SimpleDateFormat();
② Use a constructor with parameters: simpledateformat SDF1 = new simpledateformat ("yyyy MM DD HH: mm: SS");
@Test public void testSimpleDateFormat() throws ParseException { //Instantiate SimpleDateFormat: use default constructor SimpleDateFormat sdf = new SimpleDateFormat(); //Format: date -- > string Date date = new Date(); System.out.println(date);//Sun Jan 30 22:26:22 CST 2022 String format = sdf.format(date); System.out.println(format);//22-1-30 10:26 PM //Parsing: inverse process of formatting, string -- > date String str = "19-12-18 11 a.m:43"; Date date1 = sdf.parse(str); System.out.println(date1);//Wed Dec 18 11:43:00 CST 2019 //*************Format and parse in the specified way: call the constructor with parameters***************** // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //format String format1 = sdf1.format(date); System.out.println(format1);//2022-01-30 10:26:22 //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters), //Otherwise, throw the exception Date date2 = sdf1.parse("2020-02-18 11:48:27"); System.out.println(date2);//Tue Feb 18 11:48:27 CST 2020 }
eg: the string "2020-09-08" is converted to Java sql. Date
@Test public void testExer(){ String birth = "2020-09-08"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(birth); //Parsing: String -- > date java.sql.Date birthDate = new java.sql.Date(date.getTime()); System.out.println(birthDate); }
3, JDK date in API 8
1,LocalDate,LocalTime,LocalDateTime
now(): get the current date, time and date + time
of(): set the specified year, month, day, hour, minute and second. No offset.
getXxx(): get related properties
withXxx(): set related properties -- > to reflect immutability
@Test public void test1(){ //now(): get the current date, time and date + time LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); //of(): set the specified year, month, day, hour, minute and second. No offset LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43); System.out.println(localDateTime1); //getXxx(): get related properties System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getMinute()); //Reflect immutability //withXxx(): set related properties LocalDate localDate1 = localDate.withDayOfMonth(22); System.out.println(localDate); System.out.println(localDate1); LocalDateTime localDateTime2 = localDateTime.withHour(4); System.out.println(localDateTime); System.out.println(localDateTime2); //Immutability LocalDateTime localDateTime3 = localDateTime.plusMonths(3); System.out.println(localDateTime); System.out.println(localDateTime3); LocalDateTime localDateTime4 = localDateTime.minusDays(6); System.out.println(localDateTime); System.out.println(localDateTime4); }
explain:
LocalDateTime is used more frequently than LocalDate and LocalTime, similar to Calendar.
2,Instant
now(): get the standard time corresponding to the original meridian
atOffset(): adds the offset of the time
Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class
Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds
@Test public void test2(){ //now(): get the standard time corresponding to the original meridian Instant instant = Instant.now(); System.out.println(instant);//2019-02-18T07:29:41.719Z //Add offset of time OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00 //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class long milli = instant.toEpochMilli(); System.out.println(milli); //Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds Instant instant1 = Instant.ofEpochMilli(1550475314878L); System.out.println(instant1); }
3. DateTimeFormatter: format or parse date and time -- >, similar to SimpleDateFormat
Method 1: predefined standard format: ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
Format: date -- > string: call format()
Parse: String -- > date: call parse()
Mode 2:
① Localization related formats. For example: ofLocalizedDateTime()
FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDateTime
② Localization related formats. For example: ofLocalizedDate()
FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDate
Method 3: custom format. For example: ofpattern ("yyyy MM DD HH: mm: SS")
@Test public void test3(){ // Method 1: predefined standard format. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //Format: date -- > string LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(localDateTime); System.out.println(str1);//2019-02-18T15:42:18.797 //Parsing: String -- > date TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797"); System.out.println(parse); // Mode 2: // Localization related formats. For example: ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //format String str2 = formatter1.format(localDateTime); System.out.println(str2);//February 18, 2019 03:47:16 PM // Localization related formats. For example: ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //format String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2019-2-18 // Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS") DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //format String str4 = formatter3.format(LocalDateTime.now()); System.out.println(str4);//2019-02-18 03:52:09 //analysis TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09"); System.out.println(accessor); }
4. Other classes (System, Math, BigInteger, BigDecimal)
@Test public void test1() { String javaVersion = System.getProperty("java.version"); System.out.println("java of version:" + javaVersion); String javaHome = System.getProperty("java.home"); System.out.println("java of home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os of name:" + osName); String osVersion = System.getProperty("os.version"); System.out.println("os of version:" + osVersion); String userName = System.getProperty("user.name"); System.out.println("user of name:" + userName); String userHome = System.getProperty("user.home"); System.out.println("user of home:" + userHome); String userDir = System.getProperty("user.dir"); System.out.println("user of dir:" + userDir); } @Test public void test2() { BigInteger bi = new BigInteger("1243324112234324324325235245346567657653"); BigDecimal bd = new BigDecimal("12435.351"); BigDecimal bd2 = new BigDecimal("11"); System.out.println(bi); // System.out.println(bd.divide(bd2)); System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP)); System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP)); }
4, Java comparator
explain:
① Under normal circumstances, objects in Java can only be compared: = = or! =. You cannot use > or <. However, in the actual development scenario, we need to sort mu lt iple objects. By implication, we need to compare the size of objects. How? Use either of the two interfaces: Comparable or} Comparator
② Comparison between Comparable interface and Comparator:
Once the method of the Comparable interface is determined, ensure that the object of the implementation class of the Comparable interface can be compared in size at any position; The Comparator interface is a temporary comparison.
1. Use of Comparable interface: natural sorting
① For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the sizes of two objects.
② For example, String and wrapper classes are arranged from small to large after rewriting the compareTo() method.
③ Rules for rewriting compareTo(obj):
If the current object this is greater than the formal parameter object obj, a positive integer is returned;
If the current object this is less than the formal parameter object obj, a negative integer is returned;
If the current object this is equal to the parameter object obj, zero is returned.
④ For custom classes, if sorting is required, we can let the custom class implement the Comparable interface, override the compareTo(obj) method, and specify how to sort in the compareTo(obj) method.
public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low @Override public int compareTo(Object o){ if(o instanceof Goods){ Goods goods = (Goods)o; //Mode 1: if(this.price > goods.price){ return 1; }else if(this.price < goods.price){ return -1; }else{ //return 0; return -this.name.compareTo(goods.name); } //Method 2: return double compare(this.price,goods.price); } throw new RuntimeException("The data type passed in is inconsistent!"); } }
@Test public void test2(){ Goods[] arr = new Goods[5]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("microsoftMouse",43); Arrays.sort(arr); System.out.println(Arrays.toString(arr)); }
2. Use of Comparator interface: custom sorting
① Background: when a custom class does not implement Java Lang. comparable interface, which is not convenient to modify the code, or implements Java The sorting rules of the lang. comparable interface are not suitable for the current operation, so you can consider using the Comparator object to sort.
② Rewrite the compare(Object o1,Object o2) method to compare the sizes of o1 and o2:
If the method returns a positive integer, o1 is greater than o2;
If 0 is returned, it means equal;
If a negative integer is returned, o1 is less than o2.
@Test public void test3(){ String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"}; Arrays.sort(arr,new Comparator(){ //Arrange strings in descending order @Override public int compare(Object o1,Object o2){ if(o1 instanceof String && o2 instanceof String){ String s1 = (String)o1; String s2 = (String)o2; return -s1.compareTo(s2); } throw new RuntimeException("The input data type is inconsistent!"); } }); System.out.println(Arrays.toString(arr)); }
@Test public void test4(){ Goods[] arr = new Goods[6]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("huaweiMouse",224); arr[5] = new Goods("microsoftMouse",43); Arrays.sort(arr,new Comparator(){ //Specify the way to compare the size of goods: sort according to the product name from low to high, and then sort according to the price from high to low @Override public int compare(Object o1,Object o2){ if(o1 instanceof Goods && o2 instanceof Goods){ Goods g1 = (Goods)o1; Goods g2 = (Goods)o2; if(g1.getName().equals(g2.getName())){ return -Double.compare(g1.getPrice(),g2.getPrice()); }else{ return g1.getName().compareTo(g2.getName()); } } throw new RuntimeException("The input data type is inconsistent!"); } }); System.out.println(Arrays.toString(arr)); }
Summary:
1. Inherit the Comparable interface and implement the CompareTo(obj) method
2. Create the implementation class object of the Comparator interface and implement the compare(Object o1,Object o2) method
3. String and wrapper classes inherit the Comparable interface and implement the CompareTo(obj) method
4. The wrapper class also provides a compare (basic data type x, basic data type y) static method