一、String類
java.lang.String
類的使用
(一)概述
String:字串,使用一對""引起來表示。
-
String宣告為final的,不可被繼承
-
String 實現了
Serializable
介面:表示字串是支援序列化的。 實現了Comparable
介面:表示String可以比較大小 -
String內部定義了
final char[] value
用於儲存字串資料 -
String:代表不可變的字元序列。簡稱:不可變性。
體現:
4.1.當對字串重新賦值時,需要重寫指定記憶體區域賦值,不能使用原有的value進行賦值。
4.2.當對現有的字串進行連線操作時,也需要重新指定記憶體區域賦值,不能使用原有的value進行賦值。
4.3.當呼叫String的
replace()
方法修改指定字元或字串時,也需要重新指定記憶體區域賦值,不能使用原有的value進行賦值。 -
透過字面量的方式(區別於new給一個字串賦值,此時的字串值宣告在字串常量池中)。
-
字串常量池中是不會儲存相同內容(使用String類的equals()比較,返回true)的字串的)。
(二)String的特性
String類:代表字串。Java程式中的所有字串字面值(如"abc")都作為此類的例項實現。 String是一個final類,代表不可變的字元序列。 字串是常量,用雙引號引起來表示。它們的值在建立之後不能更改。 String物件的字元內容是儲存在一個字元陣列vaue[]中的。
String原始碼構造器:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
1. String的不可變性
1.1 說明:
- 當對字串重新賦值時,需要重寫指定記憶體區域賦值,不能使用原有的value進行賦值。
- 當對現的字串進行連線操作時,也需要重新指定記憶體區域賦值,不能使用原有的value進行賦值。
- 當呼叫String的
replace()
方法修改指定字元或字串時,也需要重新指定記憶體區域賦值,不能使用原有的value進行賦值。
1.2 程式碼舉例:
String s1 = "abc";//透過字面量的定義方式
String s2 = "def";
s1 = "hello";
System.out.println(s1 == s2); //false 比較s1與s2的地址值
System.out.println(s1);//hello
System.out.println(s2);//def
System.out.println("-----------------------");
String s3 = "abc";
s3 += "def";
System.out.println(s3);//abcdef
System.out.println(s2);//def
System.out.println("-----------------------");
String s4 ="test";
String s5 = s4.replace("t","b");
System.out.println(s4);//test
System.out.println(s5);//besb
1.3 圖示解析:
2. String例項化方法
2.1 實現方式說明:
- 方式一:透過字面量定義的方式
- 方式二:透過new + 構造器的方式
面試題:
String s = new String("abc");
方式建立物件,在記憶體中建立了幾個物件?
兩個:一個是堆空間中new結構,另一個是char[]
對應的常量池中的資料:"abc"
2.2 程式碼例項:
//透過字面量定義的方式:此時的s1和s2的資料javaEE宣告在方法區中的字串常量池中。
String s1 = "javaEE";
String s2 = "javaEE";
//透過new + 構造器的方式:此時的s3和s4儲存的地址值,是資料在堆空間中開闢空間以後對應的地址值。
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
String str1=“abc”;
與 String str2= new String(“abc”);
的區別?
新建String物件的記憶體解析
3. 字串拼接方式賦值對比
3.1說明:
- 常量與常量的拼接結果在常量池。且常量池中不會存在相同內容的常量。
- 只要其中一個是變數,結果就在堆中。
- 如果拼接的結果呼叫
intern()
方法,返回值就在常量池中
3.2 程式碼示例
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();//返回值得到的s8使用的常量值中已經存在的“javaEEhadoop”
System.out.println(s3 == s8);//true
****************************
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false
final String s4 = "javaEE";//s4:常量
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true
記憶體解析
4. String使用陷阱
-
String s1="a";
說明:在字串常量池中建立了一個字面量為"a"的字串。
-
s1=s1+"b"
說明:實際上原來的“a”字串物件已經丟棄了,現在在堆空間中產生了一個字串s1+"b"(也就是"ab")。如果多次執行這些改變串內容的操作,會導致大量副本字串物件存留在記憶體中,降低效率。如果這樣的操作放到迴圈中,會極大影響程式的效能。
-
String s2="ab";
說明:直接在字串常量池中建立一個字面量為"ab"的字串。 -
String s3="a"+"b";
說明:s3指向字串常量池中已經建立的"ab"的字串。 -
String s4=s1.intern();
說明:堆空間的S1物件在呼叫 intern()之後,會將常量池中已經存在的"ab"字串賦值給s4。
5. String類常用方法
5.1 字串操作
操作字元:
int length()
:返回字串的長度:return value.length
char charAt(int index)
: 返回某索引處的字元return value[index]
boolean isEmpty()
:判斷是否是空字串:return value.length == 0
String toLowerCase()
:使用預設語言環境,將 String 中的所字元轉換為小寫String toUpperCase()
:使用預設語言環境,將 String 中的所字元轉換為大寫String trim()
:返回字串的副本,忽略前導空白和尾部空白boolean equals(Object obj)
:比較字串的內容是否相同boolean equalsIgnoreCase(String anotherString)
:與equals()
方法類似,忽略大小寫String concat(String str)
:將指定字串連線到此字串的結尾。 等價於用+
int compareTo(String anotherString)
:比較兩個字串的大小String substring(int beginIndex)
:返回一個新的字串,它是此字串的從beginIndex 開始擷取到最後的一個子字串。String substring(int beginIndex, int endIndex)
:返回一個新字串,它是此字串從 beginIndex 開始擷取到 endIndex (不包含)的一個子字串。
程式碼示例:
@Test
public void test2() {
String s1 = "helloword";
System.out.println(s1.length());//9
System.out.println(s1.charAt(4));//o
System.out.println(s1.isEmpty());//false
String s2 = "HELLOword";
System.out.println(s2.toLowerCase());//hellowod
System.out.println(s2.toUpperCase());//HELLOWORD
String s3 = " hello word ";
System.out.println(s3.trim());//hello word
String s4 = "helloword";
System.out.println(s4.equals(s1));//true
System.out.println(s4.equalsIgnoreCase(s2));//true
String s5 = "hello";
System.out.println(s5.compareTo(s4));//-4 相等時返回0,小的時候返回負數
System.out.println(s4.compareTo(s1));//0
System.out.println(s4.substring(5));//word
System.out.println(s4.substring(5, 9));//word,取值範圍左開右閉
}
判斷字元:
boolean endsWith(String suffix)
:測試此字串是否以指定的字尾結束boolean startsWith(String prefix)
:測試此字串是否以指定的字首開始boolean startsWith(String prefix, int toffset)
:測試此字串從指定索引開始的子字串是否以指定字首開始
@Test
public void test3() {
String s1 = "javaEE";
System.out.println(s1.endsWith("EE"));//true
System.out.println(s1.startsWith("a"));//false
System.out.println(s1.startsWith("EE", 4));//true
}
5.2 查詢字串中的字元
boolean contains(CharSequence s):
當且僅當此字串包含指定的 char 值序列時,返回 trueint indexOf(String str)
:返回指定子字串在此字串中第一次出現處的索引int indexOf(String str, int fromIndex)
:返回指定子字串在此字串中第一次出現處的索引,從指定的索引開始int lastIndexOf(String str)
:返回指定子字串在此字串中最右邊出現處的索引int lastIndexOf(String str, int fromIndex)
:返回指定子字串在此字串中最後一次出現處的索引,從指定的索引開始反向搜尋
注:
indexOf
和lastIndexOf
方法如果未找到都是返回-1
程式碼示例:
@Test
public void test3() {
String s2="hello word";
System.out.println(s2.contains("o"));//true
System.out.println(s2.indexOf("h"));//0
System.out.println(s2.indexOf("o", 5));//7
System.out.println(s2.lastIndexOf("o"));//7
System.out.println(s2.lastIndexOf("l", 2));//2
}
5.3 字串操作方法
- 替換:
String replace(char oldChar, char newChar)
:返回一個新的字串,它是透過用 newChar 替換此字串中出現的所 oldChar 得到的。String replace(CharSequence target, CharSequence replacement)
:使用指定的字面值替換序列替換此字串所匹配字面值目標序列的子字串。String replaceAll(String regex, String replacement)
:使用給定的 replacement 替換此字串所匹配給定的正規表示式的子字串。String replaceFirst(String regex, String replacement)
:使用給定的 replacement 替換此字串匹配給定的正規表示式的第一個子字串。
- 匹配:
boolean matches(String regex)
:告知此字串是否匹配給定的正規表示式。
- 切片:
String[] split(String regex)
:根據給定正規表示式的匹配拆分此字串。String[] split(String regex, int limit)
:根據匹配給定的正規表示式來拆分此字串,最多不超過limit個,如果超過了,剩下的全部都放到最後一個元素中。
程式碼示例:
@Test
public void test4() {
String str1 = "北京你好,你好北京";
String str2 = str1.replace('北', '南');
System.out.println(str1);//北京你好,你好北京
System.out.println(str2);//南京你好,你好南京
String str3 = str1.replace("北京", "上海");
System.out.println(str3);//上海你好,你好上海
System.out.println("*************************");
String str = "12hello34world5java7891mysql456";
//把字串中的數字替換成,,如果結果中開頭和結尾有,的話去掉
String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
System.out.println(string);//hello,world,java,mysql
System.out.println("*************************");
str = "12345";
//判斷str字串中是否全部有數字組成,即有1-n個數字組成
boolean matches = str.matches("\\d+");
System.out.println(matches);//true
String tel = "0571-4534289";
//判斷這是否是一個杭州的固定電話
boolean result = tel.matches("0571-\\d{7,8}");
System.out.println(result);//true
System.out.println("*************************");
str = "hello|world|java";
String[] strs = str.split("\\|");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);//依次輸出hello word java
}
System.out.println();
str2 = "hello.world.java";
String[] strs2 = str2.split("\\.");
for (int i = 0; i < strs2.length; i++) {
System.out.println(strs2[i]);//依次輸出hello word java
}
}
6. String與其他結構的轉換
6.1 String與基本資料型別、包裝類之間的轉換
String --> 基本資料型別、包裝類:呼叫包裝類的靜態方法:parseXxx(str)
基本資料型別、包裝類 --> String:呼叫String過載的 valueOf(xxx)
程式碼示例:
@Test
public void StringToBasic() {
String str1 = "123";
int i = Integer.parseInt(str1);
System.out.println(i);
System.out.println(i == 123);//true
int j = 456;
String s = String.valueOf(j);
System.out.println(s);
System.out.println(s.equals("456"));//true
}
6.2 與字元陣列之間的轉換
String --> char[]:呼叫String的 toCharArray() char[]
--> String:呼叫String的構造器
程式碼示例:
@Test
public void BasicToString() {
String s1 = "helloword";
char[] chars = s1.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
char[] charArray = new char[]{'h', 'e', 'l', 'l', 'o'};
String s2 = new String(charArray);
System.out.println(s2);
}
6.3 與位元組陣列之間的轉換
編碼:String --> byte[]:呼叫String的 getBytes()
解碼:byte[] --> String:呼叫String的構造器
編碼:字串 -->位元組 (看得懂 --->看不懂的二進位制資料)
解碼:編碼的逆過程,位元組 --> 字串 (看不懂的二進位制資料 ---> 看得懂
說明:解碼時,要求解碼使用的字符集必須與編碼時使用的字符集一致,否則會出現亂碼。
@Test
public void StringToByteTest() throws UnsupportedEncodingException {
String s1 ="你好java世界";
byte[] bytesArray = s1.getBytes();//使用預設字符集編碼
System.out.println(Arrays.toString(bytesArray));//[-28, -67, -96, -27, -91, -67, 106, 97, 118, 97, -28, -72, -106, -25, -107, -116]
byte[] gbks = s1.getBytes("gbk");//使用gbk編碼集合
System.out.println(Arrays.toString(gbks));//[-60, -29, -70, -61, 106, 97, 118, 97, -54, -64, -67, -25]
System.out.println("--------------------------------");
String str1=new String(bytesArray);//使用預設字元進行解碼
System.out.println(str1);//你好java世界
String str2 = new String(gbks);//使用預設字元對gbk編碼進行解碼
System.out.println(str2);//���java����解碼錯誤,出現中文亂碼,原因:編碼和解碼不一致
String str3 = new String(gbks,"gbk");//使用gbk格式進行解碼
System.out.println(str3);//你好java世界,解碼正確,原因:編碼和解碼一致
}
6.4 與StringBuffer、StringBuilder之間的轉換
1.String -->StringBuffer、StringBuilder: 呼叫StringBuffer、StringBuilder構造器
@Test
public void StringToStringBufferTest(){
String str1 ="helloword";
StringBuffer stringBuffer = new StringBuffer(str1);
System.out.println(stringBuffer);//helloword
StringBuilder stringBuilder = new StringBuilder(str1);
System.out.println(stringBuilder);//helloword
stringBuffer.append("isStringBuffer");
System.out.println(stringBuffer);//hellowordandgood
stringBuilder.append("isStringBuider");
System.out.println(stringBuilder);
}
2.StringBuffer、StringBuilder -->String:
①呼叫String構造器; ②StringBuffer、StringBuilder的toString()
@Test
public void StringBuiderOrStringBufferToStringTest() {
StringBuffer sb1 = new StringBuffer("hello StringBuffer");
System.out.println(sb1);
StringBuilder sb2 = new StringBuilder("hello StringBuider");
System.out.println(sb2);
System.out.println("----------------------");
String str1 = new String(sb1);
System.out.println(str1);
String str2 = new String(sb2);
System.out.println(str2);
System.out.println("----------------------");
System.out.println(sb1.toString());
System.out.println(sb2.toString());
}
7. JVM中字串常量池存放位置說明:
jdk 1.6 (jdk 6.0 ,java 6.0):字串常量池儲存在方法區(永久區)
jdk 1.7:字串常量池儲存在堆空間
jdk 1.8:字串常量池儲存在方法區(元空間)
8. 常見演算法題目的考查:
1)模擬一個trim方法,去除字串兩端的空格。
public String myTrim(String str) {
if (str != null) {
int start = 0;//記錄從前往後首次索引位置不是空格的位置索引
int end = str.length() - 1;//記錄從後往前首次索引位置不是空格的位置索引
while (start < end && str.charAt(start) == ' ') {
start++;
}
while (start < end && str.charAt(end) == ' ') {
end--;
}
if (str.charAt(start) == ' ') {
return "";
}
return str.substring(start, end + 1);
}
return null;
}
2)將一個字串進行反轉。將字串中指定部分進行反轉。比如“abcdefg”反轉為”abfedcg”
//方式一 轉化為char型陣列反轉需要的部分
public String reverse1(String str, int start, int end) {
if (str != null) {
//1.轉換成char型陣列
char[] charArray = str.toCharArray();
//2.進行反轉操作
for (int i = start, j = end; i < j; i++, j--) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
//3.返回值
return new String(charArray);
}
return null;
}
//方式二
//分析:整個字串分為三部分不反轉的、反轉的、不反轉的
//先將前面不反轉的部分取出來,將反轉的部分取出後進行拼接
public String reverse2(String string, int start, int end) {
if(string != null){
//第一部分
String newStr = string.substring(0, start);
//第二部分
for (int i = end; i >= start; i--) {
newStr += string.charAt(i);
}
//第三部分
newStr += string.substring(end + 1);
//拼接操作
return newStr;
}
return null;
}
//方式三,使用StringBuffer或StringBuilder替換String最佳化
public String reverse3(String str, int start, int end) {
if(str != null){
//1.新建StringBuffer
StringBuffer stringBuffer = new StringBuffer(str.length());
//2.第一部分
stringBuffer.append(str.substring(0, start));
//3.第二部分
for (int i = end; i >= start; i--) {
stringBuffer.append(str.charAt(i));
}
//4.第三部分
stringBuffer.append(str.substring(end + 1));
//5.拼接操作
return stringBuffer.toString();
}
return null;
}
3)獲取一個字串在另一個字串中出現的次數。 比如:獲取“ ab”在 “abkkcadkabkebfkabkskab” 中出現的次數
public int count(String mainStr, String subStr) {
//1.判斷主串和部分串的大小
if (mainStr.length() >= subStr.length()) {
int index = 0;
int count = 0;
//2.在主串中取出子串下標,並將新的下標賦值給主串,統計量加1
// while ((index = mainStr.indexOf(subStr) )!= -1){
// count++;
// //從已經找到的子串的下一個開始
// mainStr = mainStr.substring(index + subStr.length());
// }
//改進,不再新建字串,只做位置比對
while ((index = mainStr.indexOf(subStr, index)) != -1) {
index += subStr.length();
count++;
}
return count;
} else {
return 0;
}
}
4)獲取兩個字串中最大相同子串。比如: str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm" 提示:將短的那個串進行長度依次遞減的子串與較長的串比較。
//只存在一個子串的情況
public String getMaxSameSubString(String str1, String str2) {
//1.判斷兩個字串的大小
if (str1 != null && str2 != null) {
String maxStr = (str1.length() >= str2.length()) ? str1 : str2;
String minStr = (str1.length() < str2.length()) ? str1 : str2;
int len = minStr.length();
//2.用小的依次去比對大的子串
for (int i = 0; i < len; i++) {//這層for迴圈用來確定需要比對的字元次數
for (int x = 0, y = len - i; y <= len; x++, y++) {
if (maxStr.contains(minStr.substring(x, y))) {
return minStr.substring(x, y);
}
}
}
}
return null;
}
//存在多個相同子串的情況
// 此時先返回String[],後面可以用集合中的ArrayList替換,較方便
public String [] getMaxSameSubStrings(String str1, String str2) {
//1.先比較出兩個子串的大小
if (str1 != null && str2 != null) {
StringBuffer stringBuffer = new StringBuffer();
String maxStr = (str1.length() > str2.length()) ? str1 : str2;
String minStr = (str1.length() > str2.length()) ? str2 : str1;
//2.用小的去依次匹配大的
int len = minStr.length();
for (int i = 0; i < len; i++) {
for (int x = 0, y = len - i; y <= len; x++,y++ ){
String subString = minStr.substring(x,y);
//3.取出匹配到的子串
if (maxStr.contains(subString)){
stringBuffer.append(subString+",");
}
}
//System.out.println(stringBuffer);
if (stringBuffer.length() != 0){
break;
}
}
String [] split = stringBuffer.toString().replaceAll(",$","").split("\\,");
return split;
}
return null;
}
5)對字串中字元進行自然順序排序。 提示:
- 字串變成字元陣列。
- 對陣列排序,擇,冒泡,
Arrays.sort()
; - 將排序後的陣列變成字串。
@Test
public void charTest() {
String str1 = "hello java";
char[] charArray = str1.toCharArray();
Arrays.sort(charArray);
String str2 = new String(charArray);
System.out.println(str2);
}
二、StringBuffer和StringBuilder
(一)StringBuffer類
1.概述:
java.lang.String.Buffer
代表可變的字元序列,JDK1.0中宣告,可以對字串內容進行增刪,此時不會產生新的物件。 很多方法與 String相同 作為引數傳遞時,方法內部可以改變值。
abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char[] value;//value沒有final宣告,value可以不斷擴容
/**
* The count is the number of characters used.
*/
int count;//count記錄有效字元個數
- StringBuffer類不同於 String,其物件必須使用構造器生成。
- 有三個構造器:
StringBuffer()
:初始容量為16的字串緩衝區StringBuffer(int size)
:構造指定容量的字串緩衝區StringBuffer(String str)
:將內容初始化為指定字串內容
String s= new String("我喜歡學習");
StringBuffer buffer= new StringBuffer("我喜歡學習");
buffer. append("數學");
2.常用方法:
StringBuffer append(xxx)
:提供了很多的append()
方法,用於進行字串拼接StringBuffer delete(int start,int end)
:刪除指定位置的內容StringBuffer replace(int start, int end, String str)
:把[start,end)位置替換為strStringBuffer insert(int offset, xxx)
:在指定位置插入xxxStringBuffer reverse()
:把當前字元序列逆轉
當 append和insert時,如果原來vaue陣列長度不夠,可擴容。 如上這些方法支援方法鏈操作。 方法鏈的原理:
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
public int indexOf(String str)
:返回子串的下標public String substring(int start,int end)
:返回一個從start開始到end索引結束的左閉右開區間的子字串public int length()
:獲取字串的長度public char charAt(int n )
:返回指定位置的字元public void setCharAt(int n ,char ch)
:設定指定位置的字元
總結:
增:append(xxx)
;
刪:delete(int start,int end)
;
改:setCharAt(int n ,char ch)
/ replace(int start, int end, String str)
;
查:charAt(int n )
;
插:insert(int offset, xxx)
;
長度:length()
;
遍歷:for() + charAt()
/ toString()
;
程式碼示例:
@Test
public void stringBufferMethodTest(){
StringBuffer s1 = new StringBuffer("abc");
System.out.println(s1);
System.out.println(s1.append("1"));//abc1
System.out.println(s1.delete(0, 1));//bc1
System.out.println(s1.replace(0, 1, "hello"));//helloc1
System.out.println(s1.insert(3, "v"));//helvloc1
System.out.println(s1.reverse());//1colvleh
}
(二)StringBuilder類
StringBuilder和 StringBuffer非常類似,均代表可變的字元序列,而且提供相關功能的方法也一樣,只是StringBuilder類沒有加執行緒鎖,執行效率更高。
1. String、StringBuffer、StringBuilder三者的對比
- String:不可變的字元序列;底層使用
char[]
儲存;佔用記憶體(會不斷的建立和回收物件) - StringBuffer:可變的字元序列;執行緒安全的,效率低;執行緒安全;底層使用char[]儲存;
- StringBuilder:可變的字元序列;jdk5.0新增的,執行緒不安全的,效率高;執行緒不安全;底層使用
char[]
儲存
注意:作為引數傳遞的話,方法內部Stng不會改變其值, StringBuffer和 StringBuilder會改變其值。
2. StringBuffer與StringBuilder的記憶體解析
以StringBuffer為例:
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];底層建立了一個長度是16的陣列。
System.out.println(sb1.length());//
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
StringBuffer構造器原始碼:
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
問題1. System.out.println(sb2.length());//3
問題2. 擴容問題:如果要新增的資料底層陣列盛不下了,那就需要擴容底層的陣列。 預設情況下,擴容為原來容量的2倍 + 2,同時將原有陣列中的元素複製到新的陣列中。
指導意義:開發中建議大家使用:StringBuffer(int capacity)
或 StringBuilder(int capacity)
3. 對比String、StringBuffer、StringBuilder三者的執行效率
從高到低排列:StringBuilder > StringBuffer > String
public void test3(){
//初始設定
long startTime = 0L;
long endTime = 0L;
String text = "";
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
//開始對比
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的執行時間:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的執行時間:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的執行時間:" + (endTime - startTime));
}
三、JDK 8.0以前的日期時間API
1. java.lang.System
類
System類提供的 public static long currentTimeMillis()
用來返回當前時間與1970年1月1日0時0分0秒之間以毫秒為單位的時間差。(時間戳) 此方法適於計算時間差。
計算世界時間的主要標準有:
- UTC(Coordinated Universal Time)
- GMT(Greenwich Mean Time)
- CST(Central Standard Time)
程式碼示例:
//獲取系統當前時間:System類中的currentTimeMillis()
long time = System.currentTimeMillis();
//返回當前時間與1970年1月1日0時0分0秒之間以毫秒為單位的時間差。
//稱為時間戳
System.out.println(time);
2. java.util.Date
類
表示特定的瞬間,精確到毫秒
2.1 構造器
Date()
:使用無參的構造器建立物件可以獲取本地當前時間
Date(long date)
2.2 常用方法
getTime()
:返回自1970年1月1日00:00:00GMT以來此Date物件表示的毫秒數
tostring()
:把此Date物件轉換為以下形式的 String:
- dow mon dd
- hh: mm:ss zzz yyyy
其中:doW是一週中的某一天(Sun,Mon,Tue,Wed,Thu,Fri,Sat),zzz是時間標準。 其它很多方法都過時了
2.3 java.util.Date類與java.sql.Date
類
java.util.Date
類java.sql.Date
類
1.兩個構造器的使用
- 構造器一:
Date()
:建立一個對應當前時間的Date物件 - 構造器二:建立指定毫秒數的Date物件
2.兩個方法的使用
toString()
:顯示當前的年、月、日、時、分、秒getTime()
:獲取當前Date物件對應的毫秒數。(時間戳)
3.java.sql.Date
對應著資料庫中的日期型別的變數
如何將 java.util.Date
物件轉換為 java.sql.Date
物件
@Test
public void dateTest(){
//構造器一:Date():建立一個對應當前時間的Date物件
Date date1 = new Date();
System.out.println(date1.toString());//Sun Apr 19 13:35:12 CST 2020
System.out.println(date1.getTime());//1587274512876
//構造器二:建立指定毫秒數的Date物件
Date date2 = new Date(15872745176L);
System.out.println(date2.toString());
System.out.println("-----------------------");
//建立java.sql.Date物件
java.sql.Date date3 = new java.sql.Date(1587274512876L);
System.out.println(date3.toString());
//如何將java.util.Date物件轉換為java.sql.Date物件
Date date4 = new Date();
//第一種方式,存在問題:java.util.Date cannot be cast to java.sql.Date
// java.sql.Date date6 = (java.sql.Date) date4;
// System.out.println(date6);
//第二種方式
java.sql.Date date5 = new java.sql.Date(date4.getTime());
System.out.println(date5);
}
3. java.text.SimpleDateFormat
類
Date類的AP不易於國際化,大部分被廢棄了, java.text.SimpleDateFormat
類是一個不與語言環境有關的方式來格式化和解析日期的具體類。
它允許進行格式化:日期→文字、解析:文字→日期
格式化:
SimpleDateFormat()
:預設的模式和語言環境建立物件
public SimpleDateFormat(String pattern)
:該構造方法可以用引數 pattern指定的格式建立一個物件,該物件呼叫:
public String format(Datedate)
:方法格式化時間物件date
解析: public Date parse(String source)
:從給定字串的開始解析文字,以生成個日期
1. SimpleDateFormat對日期Date類的格式化和解析
兩個操作:
1.1 格式化:日期 --->字串
1.2 解析:格式化的逆過程,字串 ---> 日期
2. SimpleDateFormat
的例項化:new + 構造器
照指定的方式格式化和解析:呼叫帶參的構造器
java
複製程式碼SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
程式碼示例:
@Test
public void test2() throws ParseException {
//例項化Date物件
Date date1 = new Date();
//例項化SimpleDateFormate物件,並設定顯示格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:aaa");
//格式化date物件
String format = simpleDateFormat.format(date1);
System.out.println(format.toString());//2020-09-19 02:09:下午
//解析:要求字串必須是符合SimpleDateFormat識別的格式(透過構造器引數體現),
//否則,拋異常
Date date2 = simpleDateFormat.parse("2020-04-20 14:20:下午");
System.out.println(date2.toString());//Tue Jan 21 02:20:00 CST 2020
}
小練習:
將字串"2020-09-08"轉換為 java.sql.Date
格式的時間
@Test
public void test3() throws ParseException {
String brith = "1997-10-15";
//新建SimpleDateFormat物件並設定時間格式
SimpleDateFormat simpBrith = new SimpleDateFormat("yyyy-mm-dd");
//將字串格式的時間格式化為Date類
Date brithday = simpBrith.parse(brith);
//透過Date的getTime方法將Date物件轉化為時間戳放到java.sql.date類的構造方法中
java.sql.Date brithDate = new java.sql.Date(brithday.getTime());
System.out.println(brithDate);
}
4. Calendar類:日曆類、抽象類
Calendar是一個抽象基類,主用用於完成日期欄位之間相互操作的功能。
- 獲取 Calenda例項的方法 使用 Calendar.getInstance()方法 呼叫它的子類 GregorianCalendarl的構造器。
- 一個 Calendar的例項是系統時間的抽象表示,透過 get(int field)方法來取得想要的時間資訊。 比如YEAR、MONTH、DAY_OF_WEEK、HOUR_OF_DAY、MINUTE、SECOND
注意: 獲取月份時:一月是0,二月是1,以此類推,12月是11 獲取星期時:週日是1,週二是2,。。。週六是7
4.1 例項化
方式一:建立其子類(GregorianCalendar)的物件
方式二:呼叫其靜態方法 getInstance()
java
複製程式碼Calendar calendar = Calendar.getInstance();
4.2 常用方法
get()
:獲取日期
set()
:設定日期
add()
:新增、修改日期
getTime
:日曆類-->Date
setTime
:Date-->日曆類
程式碼示例:
Calendar calendar = Calendar.getInstance();
// System.out.println(calendar.getClass());
//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可變性
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);
//setTime():Date ---> 日曆類
Date date1 = new Date();
calendar.setTime(date1);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
四、JDK 8.0中新的日期時間類
1. 日期時間API的迭代:
第一代:jdk 1.0 Date類
第二代:jdk 1.1 Calendar類,一定程度上替換Date類
第三代:jdk 1.8 提出了新的一套API
2. 前兩代的問題:
可變性:像日期和時間這樣的類應該是不可變的。
偏移性:Date中的年份是從1900開始的,而月份都從0開始。
格式化:格式化只對Date用,Calendar則不行。 此外,它們也不是執行緒安全的;不能處理閏秒等。
Java 8.0中新引入的java.time API:
Java 8.0吸收了Joda-Time的精華,以一個新的開始為Java建立優秀的APl。新的java.time中包含了所有關於本地日期(LocalDate)、本地時間(Localtime)、本地日期時間(LocalDate time)、時區(ZonedDate time)和持續時間(Duration)的類。歷史悠久的Date類新增了tolnstant()方法用於把Date轉換成新的表示形式。這些新增的本地化時間日期API大大簡化了日期時間和本地化的管理。
3. Java 8.0中新的日期時間API涉及的包:
4. 本地日期、本地時間、本地日期時間的使用:
LocalDate / LocalTime / LocalDateTime
4.1 說明:
① 分別表示使用 ISO-8601日曆系統的日期、時間、日期和時間。它們提供了簡單的本地日期或時間,並不包含當前的時間資訊,也不包含與時區相關的資訊。
② LocalDateTime相較於LocalDate、LocalTime,使用頻率要高
③ 類似於Calendar
4.2 常用方法:
程式碼示例:
@Test
public void test1(){
//now():獲取當前的日期、時間、日期時間
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2020-04-21
System.out.println(localTime);//18:52:54.929
System.out.println(localDateTime);//2020-04-21T18:52:54.929
//of():設定指定的年、月、日、時、分、秒。沒有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,6,12,13,12);
System.out.println(localDateTime1);//2020-10-06T12:13:12
//getXxx():獲取相關的屬性
System.out.println(localDateTime.getDayOfMonth());//21
System.out.println(localDateTime.getDayOfWeek());//TUESDAY
System.out.println(localDateTime.getMonth());//APRIL
System.out.println(localDateTime.getMonthValue());//4
System.out.println(localDateTime.getMinute());//52
//體現不可變性
//withXxx():設定相關的屬性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);//2020-04-21
System.out.println(localDate1);//2020-04-22
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime2);//2020-04-21T04:59:17.484
//不可變性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime3);//2020-07-21T18:59:17.484
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);//2020-04-21T18:59:17.484
System.out.println(localDateTime4);//2020-04-15T18:59:17.484
}
5.時間點:Instant
5.1 說明:
① 時間線上的一個瞬時點。 概念上講,它只是簡單的表示自1970年1月1日0時0分0秒(UTC開始的秒數。)
② 類似於 java.util.Date
類
5.2 常用方法:
程式碼示例:
@Test
public void test2(){
//now():獲取本初子午線對應的標準時間
Instant instant = Instant.now();
System.out.println(instant);//2020-04-21T11:03:21.469Z
//新增時間的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2020-04-21T19:03:21.469+08:00
//toEpochMilli():獲取自1970年1月1日0時0分0秒(UTC)開始的毫秒數 ---> Date類的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli);//1587467105795
//ofEpochMilli():透過給定的毫秒數,獲取Instant例項 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1587467105795L);
System.out.println(instant1);//2020-04-21T11:05:05.795Z
}
6.日期時間格式化類:DateTimeFormatter
6.1 說明:
① 格式化或解析日期、時間
② 類似於 SimpleDateFormat
6.2 常用方法:
- 例項化方式: 預定義的標準格式。如:
ISO\_LOCAL\_DATE\_TIME;
- ISO_LOCAL_DATE;ISO_LOCAL_TIME 本地化相關的格式:
- 如:
ofLocalizedDateTime(FormatStyle.LONG)
- 自定義的格式:如:
ofPattern(“yyyy-MM-dd hh:mm:ss”)
-
常用方法:
特別的:自定義的格式。如:
ofPattern(“yyyy-MM-dd hh:mm:ss”)
程式碼示例:
@Test public void test3(){ // 方式一:預定義的標準格式。 // 如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //格式化:日期-->字串 LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(localDateTime);//2020-04-21T19:13:13.530 System.out.println(str1);//2020-04-21T19:13:13.53 //解析:字串 -->日期 TemporalAccessor parse = formatter.parse("2000-04-21T19:13:13.53"); System.out.println(parse);//{},ISO resolved to 2000-04-21T19:13:13.530 // 方式二: // 本地化相關的格式。如:ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :適用於LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //格式化 String str2 = formatter1.format(localDateTime); System.out.println(str2);//2020年4月21日 下午07時16分57秒 // 本地化相關的格式。如:ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 適用於LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //格式化 String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2020-4-21 // 重點: 方式三:自定義的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”) DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String Str4 = formatter3.format(LocalDateTime.now()); System.out.println(Str4);//2020-04-21 07:24:04 TemporalAccessor accessor = formatter3.parse("2020-02-03 05:23:06"); System.out.println(accessor);//{SecondOfMinute=6, HourOfAmPm=5, NanoOfSecond=0, MicroOfSecond=0, MinuteOfHour=23, MilliOfSecond=0},ISO resolved to 2020-02-03 }
7.其它API的使用:
7.1 帶時區的日期時間:
ZonedDateTime / ZoneId
程式碼示例:
// ZoneId:類中包含了所的時區資訊
@Test
public void test1(){
//getAvailableZoneIds():獲取所的ZoneId
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
for(String s : zoneIds){
System.out.println(s);
}
System.out.println();
//獲取“Asia/Tokyo”時區對應的時間
LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(localDateTime);
}
//ZonedDateTime:帶時區的日期時間
@Test
public void test2(){
//now():獲取本時區的ZonedDateTime物件
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime);
//now(ZoneId id):獲取指定時區的ZonedDateTime物件
ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(zonedDateTime1);
}
7.2 時間間隔:
Duration--用於計算兩個“時間”間隔,以秒和納秒為基準
程式碼示例:
@Test
public void test3(){
LocalTime localTime = LocalTime.now();
LocalTime localTime1 = LocalTime.of(15, 23, 32);
//between():靜態方法,返回Duration物件,表示兩個時間的間隔
Duration duration = Duration.between(localTime1, localTime);
System.out.println(duration);
System.out.println(duration.getSeconds());
System.out.println(duration.getNano());
LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);
LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);
Duration duration1 = Duration.between(localDateTime1, localDateTime);
System.out.println(duration1.toDays());
}
7.3 日期間隔:
Period --用於計算兩個“日期”間隔,以年、月、日衡量
程式碼示例:
@Test
public void test4(){
LocalDate localDate = LocalDate.now();
LocalDate localDate1 = LocalDate.of(2028, 3, 18);
Period period = Period.between(localDate, localDate1);
System.out.println(period);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
Period period1 = period.withYears(2);
System.out.println(period1);
}
7.4 日期時間校正器:TemporalAdjuster
程式碼示例:
@Test
public void test5(){
//獲取當前日期的下一個週日是哪天?
TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
System.out.println(localDateTime);
//獲取下一個工作日是哪天?
LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){
@Override
public Temporal adjustInto(Temporal temporal) {
LocalDate date = (LocalDate)temporal;
if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
return date.plusDays(3);
}else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
return date.plusDays(2);
}else{
return date.plusDays(1);
}
}
});
System.out.println("下一個工作日是:" + localDate);
}
7.5 新的日期API與原來API的轉化問題:
五、Java比較器
1. Java比較器的使用背景:
- Java中的物件,正常情況下,只能進行比較:
==
或!=
。不能使用>
或<
的 - 但是在開發場景中,我們需要對多個物件進行排序,言外之意,就需要比較物件的大小。
- 如何實現?使用兩個介面中的任何一個:Comparable(自然排序) 或 Comparator(定製排序)
2. 自然排序:使用Comparable介面
2.1 說明
- 像 String 或包裝類等實現了Comparable介面,重寫了
compareTo(obj)
方法,給出了比較兩個物件大小的方式。 - 像 String 或包裝類重寫
compareTo()
方法以後,進行了從小到大的排列 - 重寫
compareTo(obj)
的規則: 如果當前物件this大於形參物件obj,則返回正整數, 如果當前物件this小於形參物件obj,則返回負整數, 如果當前物件this等於形參物件obj,則返回零。 - 對於自定義類來說,如果需要排序,我們可以讓自定義類實現Comparable介面,重寫
compareTo(obj)
方法。在compareTo(obj)
方法中指明如何排序 - Comparable的典型實現:(預設都是從小到大排列的) String:按照字串中字元的Uincode值進行比較 Character:按照字元的 Unicode值來進行比較 數值型別對應的包裝類以及 BigInteger、BigDecimal:按照它們對應的數值大小進行比較 Boolean:true對應的包裝類例項大於false對應的包裝類例項 Date、Time等:後面的日期時間比前面的日期時間大
2.2 自定義類程式碼舉例:
public class Goods implements Comparable{
private String name;
private double price;
//指明商品比較大小的方式:照價格從低到高排序,再照產品名稱從高到低排序
@Override
public int compareTo(Object o) {
// System.out.println("**************");
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;
return -this.name.compareTo(goods.name);
}
//方式二:
// return Double.compare(this.price,goods.price);
}
// return 0;
throw new RuntimeException("傳入的資料型別不一致!");
}
// getter、setter、toString()、構造器:省略
}
3. 定製排序:使用Comparator介面
3.1 說明:
- 背景:
當元素的型別沒實現 java.lang.Comparable
介面而又不方便修改程式碼,或者實現了java.lang.Comparable介面的排序規則不適合當前的操作,那麼可以考慮使用 Comparator 的物件來排序
\2. 重寫 compare(Object o1,Object o2)
方法,比較o1和o2的大小:
- 如果方法返回正整數,則表示o1大於o2;
- 如果返回0,表示相等;
- 返回負整數,表示o1小於o2。
3.2 程式碼舉例:
Comparator com = new Comparator() {
//指明商品比較大小的方式:照產品名稱從低到高排序,再照價格從高到低排序
@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("輸入的資料型別不一致");
}
}
4. 兩種排序方式對比
- Comparable介面的方式是一定的,保證Comparable介面實現類的物件在任何位置都可以比較大小。
- Comparator介面屬於臨時性的比較。
六、其他常用類
1.System類
- System類代表系統,系統級的很多屬性和控制方法都放置在該類的內部。該類位於java.lang包。
- 由於該類的構造器是private的,所以無法建立該類的物件,也就是無法例項化該類。其內部的成員變數和成員方法都是static的,所以也可以很方便的進行呼叫。
成員方法:
-
native long currentTimeMillis():
該方法的作用是返回當前的計算機時間,時間的表達格式為當前計算機時間和GMT時間(格林威治時間)1970年1月1號0時0分0秒所差的毫秒數。
-
void exit(int status)
該方法的作用是退出程式。其中 status的值為0代表正常退出,非零代表異常退出。使用該方法可以在圖形介面程式設計中實現程式的退出功能等
-
void gc()
該方法的作用是請求系統進行垃圾回收。至於系統是否立刻回收,則取決於系統中垃圾回收演算法的實現以及系統執行時的情況。
-
String getProperty(String key)
該方法的作用是獲得系統中屬性名為key的屬性對應的值。系統中常見的屬性名以及屬性的作用如下表所示:
程式碼示例:
@Test
public void test1() {
String javaVersion = System.getProperty("java.version");
System.out.println("java的version:" + javaVersion);
String javaHome = System.getProperty("java.home");
System.out.println("java的home:" + javaHome);
String osName = System.getProperty("os.name");
System.out.println("os的name:" + osName);
String osVersion = System.getProperty("os.version");
System.out.println("os的version:" + osVersion);
String userName = System.getProperty("user.name");
System.out.println("user的name:" + userName);
String userHome = System.getProperty("user.home");
System.out.println("user的home:" + userHome);
String userDir = System.getProperty("user.dir");
System.out.println("user的dir:" + userDir);
}
2.Math類
java.lang.Math
提供了一系列靜態方法用於科學計算。其方法的引數和返回值型別一般為double型。
3.BigInteger類、BigDecimal類
3.1BigInteger
java.math
包的BigInteger可以表示不可變的任意精度的整數。
BigInteger提供所有Java的基本整數運算子的對應物,並提供 java.lang.Math
的所有相關方法。另外,BigInteger還提供以下運算:模算術、GCD計算、質數測試、素數生成、位操作以及一些其他操作。
構造器: BigInteger(String val)
:根據字串構建 BigInteger物件
程式碼舉例:
@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));
}
3.2 BigDecimal
要求數字精度比較高,用到 java.math.BigDecimal
類
BigDecimal類支援不可變的、任意精度的有符號十進位制定點數。
構造器:
public BigDecimal(double val)
public BigDecimal(String val)
常用方法:
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor, int scale, int rounding Mode)
程式碼舉例:
@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));
}