目錄
9.1:字符串相關(guān)的類:String
? ? ? ? 9.1.1:String用法
? ? ? ? 9.1.2:String方法
? ? ? ? 9.1.3:String與char[]、byte[]之間的轉(zhuǎn)換
????????9.1.4:StringBuffer和StringBuilder的使用
9.2:JDK 8之前的日期時間API
9.3:JDK 8中新日期時間API
? ? ? ? 9.3.1:LocalDate、LocalTime、LocalDateTime的使用
? ? ? ? 9.3.2:瞬時Instant
9.4:Java比較器
? ? ? ? 9.4.1:自然排序java.util.Comparable
? ? ? ? 9.4.2:定制排序java.util.Comparator
? ? ? ? 9.4.3:兩種接口的對比:
9.5:System類
9.6:Math類
9.7:BigInteger與BigDecimal
9.1:字符串相關(guān)的類:String
String是一個final類,代表不可變的字符序列
? ? ? ? 9.1.1:String用法
package com.jiayifeng.java1;
import org.junit.Test;
/**
* author xiaojia
* create 2023-09-11 8:09
*
* 快捷鍵:alt + shift + s:構(gòu)造器
*
* 一:String的使用
*/
public class StringTest {
/*
1.String實現(xiàn)了Serializable接口:表示字符串是支持序列化的
2.String實現(xiàn)了Comparable接口:表示String可以比較大小
3.String內(nèi)部定義了final char[] value用于存儲字符串數(shù)據(jù)
4.String:代表不可變的字符序列。簡稱:不可變性
體現(xiàn)1:當對字符串重新賦值時,需要重寫指定內(nèi)存區(qū)域賦值,不能使用原有的value進行賦值
體現(xiàn)2:當對現(xiàn)有的字符串進行連接操作時,也需要重新指定內(nèi)存區(qū)域賦值,不能使用原有的value進行賦值
體現(xiàn)3:當調(diào)用String的replace()方法修飾指定字符或字符串時,也需要重新指定內(nèi)存區(qū)域
5.通過字面量的方式(區(qū)別于new)給一個字符串賦值,此時的字符串值聲明在字符串常量池中
6.字符串常量池中是不會存儲相同內(nèi)容的字符串的
*/
@Test
public void test1(){
String s1 = "abc";
String s2 = "abc";
s1 = "Hello";
System.out.println(s1 == s2); //比較s1和s2的地址值
System.out.println(s1);
System.out.println(s2);
System.out.println("*********************888");
String s3 = "abc";
s3 += "def";
String s4 = "abc";
String s5 = s4.replace('a', 'm');
System.out.println(s4); //abc
System.out.println(s5); //mbc
}
/*
String的實例化方式:
方式一:通過字面量定義的方式
方式二:通過new + 構(gòu)造器的方式
面試題:String s = new String("abc");這種方式創(chuàng)建的對象,在內(nèi)存中創(chuàng)建了幾個對象?
兩個:一個是堆空間中的new結(jié)構(gòu),另一個是char[]對應的常量池中的數(shù)據(jù):"char"
*/
@Test
public void test2(){
// 通過字面量定義的方式:此時的s1和s2的數(shù)據(jù)聲明在方法區(qū)的字符串常量池中
String s1 = "javaEE";
String s2 = "javaEE";
// 通過new + 構(gòu)造器的方式:此時的s3和s4保存的地址值,是數(shù)據(jù)在堆空間中開辟以后對應的地址值
String s3 = new String("javaEE");
String s4 = new String("javaEE");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1 == s4);
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:不可變性
}
/*
字符串的特性:
1.常量與常量的拼接結(jié)果在常量池。且常量池不會存在相同內(nèi)容的常量
2.只要其中有一個是變量,結(jié)果就在堆中
3.如果拼接的結(jié)果調(diào)用intern()方法,返回值就在常量池中
*/
@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).intern();
System.out.println(s3 == s4); //true
System.out.println(s3 == s5); //false
System.out.println(s3 == s6); //false
System.out.println(s5 == s6); //false
System.out.println(s3 == s7); //true
System.out.println(s5 == s7); //false
System.out.println(s6 == s7); //false
System.out.println(s4 == s7); //true
}
}
? ? ? ? 9.1.2:String方法
package com.jiayifeng.java1;
import com.sun.xml.internal.ws.addressing.WsaActionUtil;
import org.junit.Test;
import java.util.Locale;
/**
* author xiaojia
* create 2023-09-11 14:36
*/
public class StringMethodTest {
@Test
public void test1(){
String s1 = "HelloWorld";
System.out.println(s1.length()); //返回字符串的長度:10
System.out.println(s1.charAt(0)); //返回某索引處的字符:H
System.out.println(s1.charAt(9)); //d
System.out.println(s1.isEmpty()); //判斷是否是空字符串:false
String s2 = s1.toLowerCase(); //使用默認語言環(huán)境,將String中的所有字符轉(zhuǎn)換為小寫
System.out.println(s1); //HelloWorld:s1是不可變的,仍然為原來的字符串
System.out.println(s2); //helloworld:改成小寫以后的字符串
String s3 = s1.toUpperCase(); //使用默認語言環(huán)境,將String中的所有字符轉(zhuǎn)換為大寫
System.out.println(s1); //HelloWorld
System.out.println(s3); //HELLOWORLD
String s4 = " he llo world";
String s5 = s4.trim();
System.out.println("--------" + s3 + "--------"); //返回字符串的副本,忽略前導空白和尾部空白
System.out.println("--------" + s4 + "--------");
System.out.println(s1.equals(s4)); //比較字符串的內(nèi)容是否相同":false
System.out.println(s1.equalsIgnoreCase(s4)); //與equals()方法類似,忽略大小寫:false
System.out.println(s1.concat(s4)); //將指定字符串連接到此字符串的結(jié)尾
String s6 = "abc";
String s7 = "hello";
System.out.println(s6.compareTo(s7)); //比較兩個字符串的大小,涉及到字符串排序:負數(shù)-7
String s8= "北京歡迎你!";
String s9 = s8.substring(2);
System.out.println(s8);
System.out.println(s9); //返回一個新的字符串,它是此字符串從beginIndex開始截取的:歡迎你!
System.out.println(s8.substring(2,4)); //(左閉右開)返回一個新的字符串,它是此字符串從beginIndex開始截取的,從endIndex(不包含)結(jié)束的:歡迎
}
@Test
public void test2(){
String str1 = "helloworld";
boolean b1 = str1.endsWith("ld"); //測試此字符是否以指定的后綴結(jié)束
System.out.println(b1); //true
boolean b2 = str1.startsWith("he"); //測試此字符是否以指定的前綴結(jié)束
System.out.println(b2); //true
boolean b3 = str1.startsWith("ll",2);
System.out.println(b3); //true
}
@Test
public void test3(){
// 替換
String str1 = "北京歡迎你!";
String str2 = str1.replace('北', '南'); //返回一個新的字符串
System.out.println(str1); //北京歡迎你
System.out.println(str2); //南京歡迎你
String str3 = str1.replace("北京", "上海");
System.out.println(str3); //上海歡迎你
// 匹配
// 判斷str字符串中是否全部由數(shù)字組成,即有1-n個數(shù)字組成
String str = "12345";
boolean matches = str1.matches("\\d+");
System.out.println(matches); //false
String tel = "0571-4534289";
// 判斷這是否是一個杭州的固定電話
boolean result = tel.matches("0571-\\d{7,8}");
System.out.println(result); //true
// 切片
str = "hello|world|java";
String[] strs = str.split("\\|");
for(int i = 0;i < strs.length;i++){
System.out.println(strs[i]);
}
}
}
? ? ? ? 9.1.3:String與char[]、byte[]之間的轉(zhuǎn)換
package com.jiayifeng.java2;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* author xiaojia
* create 2023-09-12 15:29
*
* 一:String與char[]之間的轉(zhuǎn)換:
* String --> char[]:調(diào)用String的toCharArray()
* char[] --> String:調(diào)用String的構(gòu)造器
*
* 二:String與byte[]之間的轉(zhuǎn)換:
* 編碼:String --> byte[]:調(diào)用String的getBytes()
* 解碼:byte[] --> String:調(diào)用String的構(gòu)造器
*
* 編碼:字符串 --> 字節(jié)(看得懂 ---> 看不懂的二進制數(shù)據(jù))
* 解碼:編碼的逆過程,字節(jié) -->(看不懂的二進制數(shù)據(jù) ---> 看得懂)
*
* 說明:解碼時,要求使用的字符集必須與編碼時使用的字符集一致,否則會出現(xiàn)亂碼
*/
public class StringTest {
@Test
public void test1(){
String str1 = "abc123";
char[] charArray = str1.toCharArray();
for(int i = 0;i < charArray.length;i++){
System.out.print(charArray[i] + " ");
}
char[] arr = new char[]{'h','e','l','l','o'};
String str2 = new String(arr);
System.out.println(str2);
}
@Test
public void test2(){
String str1 = "abc123中國";
byte[] bytes = str1.getBytes(); //使用默認的字符集,進行編碼
System.out.println(Arrays.toString(bytes));
byte[] gbks = new byte[0]; //使用gbk字符集進行編碼
try {
gbks = str1.getBytes("gbk");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
System.out.println(Arrays.toString(gbks));
System.out.println("**********");
String str2 = new String(bytes); //使用默認的字符集,進行解碼
System.out.println(str2);
String str3 = new String(gbks);
System.out.println(str3); //出現(xiàn)亂碼的原因:編碼集和解碼集不一致
String str4 = null;
try {
str4 = new String(gbks, "gbk");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
System.out.println(str4); //沒有出現(xiàn)亂碼原因:編碼集和解碼集一致
}
}
????????9.1.4:StringBuffer和StringBuilder的使用
package com.jiayifeng.java2;
import org.junit.Test;
/**
* author xiaojia
* create 2023-09-14 15:48
*
* 一:關(guān)于StringBuffer和StringBuilder的使用
*
* 二:關(guān)于StringBuffer和StringBuilder中的方法使用
*/
public class StringBufferBuilderTest {
/*
一:關(guān)于StringBuffer和StringBuilder的使用
1.String和StringBuffer和StringBuilder的異同?
String:不可變的字符序列;底層使用char[]存儲
StringBuffer:可變的字符序列;線程安全的,效率低;底層使用char[]存儲
StringBuilder:可變的字符序列;jdk5.0新增的,線程不安全的,效率高;底層使用char[]存儲
效率:StringBuilder > StringBuffer > String
源碼分析:
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];底層創(chuàng)建了一個長度是16的數(shù)組
sb1.append('a'); //value[0] = 'a';
sb1.append('b'); //value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char["abc".length() + 16];
question1: System.out.println(sb2.length()); //3
question2:擴容問題:如果要添加的數(shù)據(jù)底層數(shù)組盛不下了,那就需要擴容底層的數(shù)組
默認情況下,擴容為原來的2倍 + 2,同時將原有數(shù)組中的元素復制到新的數(shù)組中
指導意義:在開發(fā)過程中,建議大家使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)
*/
/*
總結(jié):
增:append(xxx)
刪:delete(int start,int end)
改:setCharAt(int n,char ch) / replace(int start,int end,String str)
查:charAt(int offset,xxx)
長度:length();
遍歷:for() + charAt() + toString()
*/
@Test
public void test() {
StringBuffer sb1 = new StringBuffer("abc");
sb1.setCharAt(0,'m');
System.out.println(sb1); //mbc
StringBuffer sb2 = new StringBuffer();
System.out.println(sb2.length()); //0
}
@Test
public void test2(){
StringBuffer s1 = new StringBuffer("abc");
s1.append(1);
s1.append('1'); //提供了很多的append()的方法,用于進行字符串拼接
System.out.println(s1);
s1.delete(2,4); //刪除指定位置的內(nèi)容
System.out.println(s1);
s1.replace(1,4,"hello"); //把[start,end]位置替換為str
System.out.println(s1);
s1.insert(2,false); //在指定位置插入xxx
System.out.println(s1);
s1.reverse(); //將當前字符序列逆轉(zhuǎn)
System.out.println(s1);
}
}
9.2:JDK 8之前的日期時間API
package com.jiayifeng.java3;
import com.sun.xml.internal.ws.util.xml.CDATA;
import org.junit.Test;
import java.sql.SQLOutput;
import java.util.Date;
/**
* author xiaojia
* create 2023-09-14 17:11
*
* 一:JDK 8之前日期和時間的API測試
*/
public class DateTimeTest {
/*
java.util.Date類
|---java.sql.Data類
1.兩個構(gòu)造器的使用
>構(gòu)造器一:Data():創(chuàng)建一個對應當前時間的Data對象
>構(gòu)造器二:創(chuàng)建指定毫秒數(shù)的的Date對象
2.兩個方法的使用對應的毫秒數(shù)(時間戳)
3.java.sql.Date對應著數(shù)據(jù)庫中的日期類型的變量
>如何實例化?
>如何util.Date對象轉(zhuǎn)換為sql.Date對象?
*/
@Test
public void test2(){
// 構(gòu)造器一:Data():創(chuàng)建一個對應當前時間的Data對象
Date date1 = new Date();
System.out.println(date1.toString());//Thu Sep 14 17:25:55 CST 2023
System.out.println(date1.getTime());//1694683555892
// 構(gòu)造器二:創(chuàng)建指定毫秒數(shù)的的Date對象
Date date2 = new Date(1694683555892l);
System.out.println(date2.toString());//Thu Sep 14 17:25:55 CST 2023
// 創(chuàng)建java.sql.Date對象
java.sql.Date date3 = new java.sql.Date(1694683555892L);
System.out.println(date3);//2023-09-14
// 如何util.Date對象轉(zhuǎn)換為sql.Date對象
// 情況一:
Date date4 = new java.sql.Date(1694683555892L);
java.sql.Date date5 = (java.sql.Date)date4;
// 情況二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
System.out.println(date7);//2023-09-14
}
@Test
public void test(){
// 1.System類中的currentTimeMills()
long time = System.currentTimeMillis();
// 返回當前時間與1970年1月1日0時0分0秒之間以毫秒為單位的時間差
// 稱為事件戳
System.out.println(time);
}
}
package com.jiayifeng.java3;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* author 愛編程的小賈
* create 2023-09-16 8:23
*
* 一:jdk 8之前的日期時間的API測試
*/
public class DateTime1Test {
/*
SimpleDateFormat的使用:SimpleDateFormat對日期Date類的格式化和解析
1.兩個操作
1.1:格式化:日期 ---> 字符串
1.2:解析:格式化的逆過程,字符串 ---> 日期
2.SimpleDateFormat的實例化
*/
@Test
public void test1() throws ParseException {//異常:對寫的日期字符串格式不識別,不是系統(tǒng)默認的格式
// 實例化:使用默認的構(gòu)造器
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
// 格式化:日期 ---> 字符串
Date d1 = new Date();
System.out.println(d1);//Sat Sep 16 08:35:04 CST 2023
String format = simpleDateFormat.format(d1);
System.out.println(format);//23-9-16 上午8:35
// 解析:格式化的逆過程,字符串 ---> 日期
String str = "23-9-16 上午8:35";
Date date1 = simpleDateFormat.parse(str);
System.out.println(date1);//Sat Sep 16 08:35:00 CST 2023
// ********按照指定的方式格式化和解析:調(diào)用帶參的構(gòu)造器*********************
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
// 格式化
String format1 = sdf1.format(d1);
System.out.println(format1);//02023.九月.16 公元 08:46 上午
//2023.09.16 08:48:32
// 解析
Date d2 = sdf1.parse("2023.09.16 08:48:32");
System.out.println(d2);//Sat Sep 16 08:48:32 CST 2023
}
/*
calendar日歷類(抽象類)的使用:
*/
@Test
public void test2(){
// 1.實例化
// 方式一:創(chuàng)建其子類(GregorianCalendar)的對象
// 方式二:調(diào)用其靜態(tài)方法getInstance()
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass());//class java.util.GregorianCalendar
// 2.常用方法
// get()
int days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
// set()
calendar.set(Calendar.DAY_OF_MONTH,22);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
// add()
calendar.add(Calendar.DAY_OF_MONTH,3);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
// getTime():日歷類 ---> Date
Date date = calendar.getTime();
System.out.println(date);//Mon Sep 25 09:18:09 CST 2023
// setTime():Date ---> 日歷類
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);//16
}
}
9.3:JDK 8中新日期時間API
? ? ? ? 9.3.1:LocalDate、LocalTime、LocalDateTime的使用
? ? ? ? 9.3.2:瞬時Instant
? ? ? ? ? ? ? ? 定義:時間線上的一個瞬時點,這可能被用來記錄應用程序中的時間戳(時間戳是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現(xiàn)在的總秒數(shù))
? ? ? ? ? ? ? ? 精度:納米級
? ? ? ? ? ? ? ? 1秒 = 1000毫秒 = 10^6微秒?= 10^9納秒?
package com.jiayifeng.java3;
import org.junit.Test;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
/**
* author 愛編程的小賈
* create 2023-09-16 9:20
*
* 一:jdk 8之中新日期時間API測試
*/
public class DateTimeTest2 {
/*
LocalDate、LocalTime、LocalDateTime的使用
*/
@Test
public void test1(){
// now():獲取當前的日期、時間、日期+時間
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():設置指定的年、月、日、時、分、秒。沒有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,6,13,23,33);
System.out.println(localDateTime1);
// getXxx():獲取相關(guān)屬性
System.out.println(localDateTime1.getDayOfMonth());
System.out.println(localDateTime1.getMonth());
// 體現(xiàn)不可變性
// withXxx():設置相關(guān)屬性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);//2023-09-16
System.out.println(localDate1);//2023-09-22
// 體現(xiàn)不可變性
LocalDateTime localDateTime2 = localDateTime.plusMonths(3);
System.out.println(localDateTime);//2023-09-16T09:45:52.880
System.out.println(localDateTime2);//2023-12-16T09:45:52.880
// 減:minus
}
/*
Instant的使用
*/
@Test
public void test2(){
// now():獲取本初子午線對應的標準時間
Instant instant = Instant.now();
System.out.println(instant);//2023-09-16T02:01:11.290Z(差8小時)
// 添加時間的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2023-09-16T10:02:13.971+08:00
// 獲取自1970年01月01日00時00分00秒(UTC)開始的毫秒數(shù)
long milli = instant.toEpochMilli();
System.out.println(milli);//1694830048763
// ofEpochMilli():通過給定的毫秒數(shù)獲取Instant實例
Instant instant1 = Instant.ofEpochMilli(1694829971692l);
System.out.println(instant1);//2023-09-16T02:06:11.692Z
}
/*
DateTimeFormatter:格式化或解析日期、時間
類似于SimpleDateFormat
*/
@Test
public void test(){
// 方式一:預定義的標準格式
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
// 格式化:日期 ---> 字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);//2023-09-16T10:16:54.890
System.out.println(str1);//2023-09-16T10:16:54.89
// 解析:字符串 ---> 日期
TemporalAccessor parse = formatter.parse("2023-09-16T10:16:54.89");
System.out.println(parse);//{},ISO resolved to 2023-09-16T10:16:54.890
// 方式二:本地化相關(guān)的格式
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
// 格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);//23-9-16 上午10:21
// 方式三:自定義的格式(常用)
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
// 格式化
String str4 = formatter2.format(LocalDateTime.now());
System.out.println(str4);//2023-09-16 10:28:04
// 解析
TemporalAccessor accessor = formatter2.parse("2023-09-16 10:28:04");
System.out.println(accessor);
}
}
9.4:Java比較器
? ? ? ? 9.4.1:自然排序java.util.Comparable
package com.jiayifeng.java4;
/**
* author 愛編程的小賈
* create 2023-09-16 13:26
*/
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 +
'}';
}
// 指明商品比較大小的方式:按照價格從低到高排序
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
Goods goods = (Goods)o;
// 方式一:
if(this.price > goods.price) {
return 1;
}else if(this.price < goods.price) {
return -1;
}else{
return 0;
}
}
throw new RuntimeException("傳入的數(shù)據(jù)類型不一致");
}
}
package com.jiayifeng.java4;
import org.junit.Test;
import java.util.Arrays;
/**
* author 愛編程的小賈
* create 2023-09-16 10:44
*
* 一:說明:Java中的對象,正常情況下,只能進行等于或不等于的比較。不能使用大于或小于的比較
* 但在開發(fā)場景中,我們需要對多個對象進行排序,言外之意,就需要比較對象的大小。
* 如何實現(xiàn)?使用兩個接口中的任何一個:Comparable或Comparator
*
* 二:Comparable接口的使用
*
*/
public class CompareTest {
/*
Comparable接口的使用舉例:自然排序
1.像String、包裝類等實現(xiàn)了Comparable接口,重寫了compareTo(obj)方法,給出了比較兩個對象大小的方式
2.像String、包裝類重寫compareTo()方法以后,進行了從小到大的排列
3.重寫compareTo(obj)的規(guī)則:
如果當前對象this大于形參對象obj,則返回正整數(shù)
如果當前對象this小于形參對象obj,則返回負整數(shù)
如果當前對象this等于形參對象obj,則返回零
4.對于自定義類來說,如果需要排序,我們可以讓自定義類實現(xiàn)Comparable接口,重寫compareTo(obj)方法
在compareTo(obj)方法中指明如何排序
*/
@Test
public void test1() {
String[] arr = new String[]{"AA", "CC", "KK", "GG", "JJ", "DD"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK]
}
@Test
public void test2() {
Goods[] arr = new Goods[4];
arr[0] = new Goods("lenovoMouse",34);
arr[1] = new Goods("dellMouse",12);
arr[2] = new Goods("xiaomiMouse",54);
arr[3] = new Goods("huaweiMouse",65);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
? ? ? ? 9.4.2:定制排序java.util.Comparator
package com.jiayifeng.java4;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
/**
* author 愛編程的小賈
* create 2023-09-16 13:52
*
* 一:Comparator接口的使用:定制排序
*/
public class CompareTest1 {
/*
Comparator接口的使用:
1.背景:
當元素的類型沒有實現(xiàn)java.lang.Comparable接口而又不方便修改代碼,
或者實現(xiàn)了java.lang.Comparable接口的順序規(guī)則,但又不適合當前的操作,
那么可以考慮使用Comparator的對象來排序
2.重寫compara(Object o1,Object o2)方法,比較o1,o2的大小
如果方法返回正整數(shù),則表示o1大于o2;
如果返回0,表示相等
返回負整數(shù),表示o1小于o2
*/
@Test
public void test(){
String[] arr = new String[]{"AA", "CC", "KK", "GG", "JJ", "DD"};
Arrays.sort(arr, new Comparator<String>() {
// 按照字符串從大到小的順序排列
@Override
public int compare(String o1, String o2) {
if(o1 instanceof String && o2 instanceof String){
String s1 = (String)o1;
String s2 = (String)o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("輸入的數(shù)據(jù)類型不一致");
}
});
System.out.println(Arrays.toString(arr));//[KK, JJ, GG, DD, CC, AA]
}
}
? ? ? ? 9.4.3:兩種接口的對比:
? ? ? ? Comparable接口的方式一旦確定,保證Comparable接口實現(xiàn)類的對象在任何位置都可以比較大小
? ? ? ? Comparator接口屬于臨時性的比較
9.5:System類
? ? ? ? 位于java.lang包
? ? ? ? 由于該類的構(gòu)造器是private的,所以無法創(chuàng)建該類的對象,也就是無法實例化該類。其內(nèi)部的成員變量和成員方法都是static的,所以也可以方便的進行調(diào)用
9.6:Math類
? ? ? ? java.lang.Math提供了一系列靜態(tài)方法用于科學計算,其方法的參數(shù)和返回值類型一般為double型
? ? ? ??
abs | 絕對值 |
sqrt | 平方根 |
pow(double a,double b) | a的b次冪 |
9.7:BigInteger與BigDecimal
????????BigInteger:表示不可變的任意精度的整數(shù)
? ? ? ? ? ? ? ? 構(gòu)造器:BigInteger(String val):根據(jù)字符串構(gòu)建BigInteger對象
????????BigDecimal:支持不可變的、任意精度的有符號的十進制定點數(shù)
? ? ? ? ? ? ? ? 構(gòu)造器:
? ? ? ? ? ? ? ? ? ? ? ? public BigDecimal(double val)文章來源:http://www.zghlxwxcb.cn/news/detail-706406.html
? ? ? ? ? ? ? ? ? ? ? ? public BigDecimal(String val)文章來源地址http://www.zghlxwxcb.cn/news/detail-706406.html
到了這里,關(guān)于第九章:Java常用類的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!