字符串相關的類:
String
指向同一個地址可才相等
注意這個地方,兩個person對象的name實際上指向的是同一個字符串常量池(Tom)
String常用方法
總結:?
?
1.string類的理解(以JDK8為例說明) 1.1 類的聲明 public final class Stringimplements java.io.Serializable, Comparable<String>, CharSequence > final:String是不可被繼承的 > Serializable:可序列化的接口。凡是實現此接口的類的對象就可以通過網絡或本地流進行數據的傳輸。 > Comparable:凡是實現此接口的類,其對象都可以比較大小。 1.2 內部聲明的屬性 jdk8中: private final char value[];//存儲字符串數據的容器> final :指明此value數組一旦初始化,其地址就不可變。 jdk9開始: 為了節省內存空間,做了優化 private final byte[] value;//存儲字符串數據的容器 2.字符串常量的存儲位置 > 字符串常量都存儲在字符串常量池(StringTable)中 > 字符串常量池不允許存放兩個相同的字符串常量。 > 字符串常量池,在不同的jdk版本中,存放位置不同。jdk7之前:字符串常量池存放在方法區jdk7及之后:字符串常量池存放在堆空間3.String的不可變性的理解了。 ① 當對字符串變量重新賦值時,需要重新指定一個字符串常量的位置進行賦值,不能在原有的位置修改 ②當對現有的字符申進行拼接操作時,需要重新開辟空間保存拼接以后的字符串,不能在原有的位置修改 ③ 當調用字符串的replace()替換現有的某個字符時,需要重新開辟空間保存修改以后的字符串,不能在原有的位置修改4.string實例化的兩種方式 第1種方式:String s1="hello"; 第2種方式:String s2=new String("hello");【面試題】 String s2 = new string("hello");在內存中創建了幾個對象? 一個是堆空間中new的對象。另一個是在字符串常量池中生成的字面量。5.String的連接操作:+ 情況1:常量 + 常量:結果仍然存儲在字符串常量池中 情況2:常量 + 變量 或 變量 + 變量:都會通過new的方式創建一個新的字符串,返回堆空間中此字符串對象的地址 情況3:調用字符串的intern(): 返回的是字符串常量池中字面量的地址(了解)情況4:concat(xxx): 不管是常量調用此方法,還是變量調用,同樣不管參數是常量還是變量,總之,調用完concat()方法都返回一個新new的對象。6.string的構造器和常用方法 6.1 構造器 public String():初始化新創建的 string對象,以使其表示空字符序列。 public String(string original): 初始化一個新創建的'string’對象,使其表示一個與參數相同的字符序列;換句話說,新創建的字符串是該參數字符串的副本 public String(char[] value):通過當前參數中的字符數組來構造新的String。 public String(char[] value,int offset,int count):通過字符數組的一部分來構造新的String。 public String(byte[] bytes):通過使用平臺的**默認字符集**解碼當前參數中的字節數組來構造新的String。 public String(byte[] bytes,String charsetName):通過使用指定的字符集解碼當前參數中的字節數組來構造新的String6.2 常用方法 4.StringBuffer和StringBuilder中的常用方法 增:append(xx) 刪:delete(int start, int end)deleteCharAt(int index) 改:replace(int start,int end, String str)setCharAt(int index,char c) 查:charAt(int index) 插:insert(int index,xx) 長度:length()7.String的算法練習
代碼:
public class StringDemo {@Testpublic void test1(){String s1 = "hello"; //字面量的定義方式String s2 = "hello";System.out.println(s1 == s2); //true}/*** String的不可變性* ① 當對字符串變量重新賦值時,需要重新指定一個字符串常量的位置進行賦值,不能在原有的位置修改* ②當對現有的字符申進行拼接操作時,需要重新開辟空間保存拼接以后的字符串,不能在原有的位置修改* ③ 當調用字符串的replace()替換現有的某個字符時,需要重新開辟空間保存修改以后的字符串,不能在原有的位置修改*/@Testpublic void test2(){String s1 = "hello";String s2 = "hello";s2 = "hi";System.out.println(s1); //hello}@Testpublic void test3(){String s1 = "hello";String s2 = "hello";s2 += "world";System.out.println(s1);//helloSystem.out.println(s2); //helloworld}@Testpublic void test4(){String s1 = "hello";String s2 = "hello";String s3 = s2.replace('l', 'w');System.out.println(s1);//helloSystem.out.println(s2);//helloSystem.out.println(s3);//hewwo}
}
練習2:
?
public class StringDemo1 {@Testpublic void test1(){String s1 = "hello";String s2 = "hello";String s3 = new String("hello");String s4 = new String("hello");System.out.println(s1 == s2); // trueSystem.out.println(s1 == s3); // falseSystem.out.println(s1 == s4);//falseSystem.out.println(s3 == s4);//falseSystem.out.println(s1.equals(s2));//true}/*** String s = new String("hello");的內存解析?或:** String s = new String("hello");在內存中創建了幾個對象?*/@Testpublic void test2(){Person p1 = new Person();Person p2 = new Person();p1.name = "Tom";p2.name = "Jerry";System.out.println(p2.name); //Tom}/*** 測試String的連接符 +*/@Testpublic void test3(){String s1 = "hello";String s2 = "world";String s3 = "helloworld";String s4 = "hello" + "world";String s5 = s1 + "world"; // 通過查看字節碼文件發現調用了StringBuilder的toString() ---> new String()String s6 = "hello" + s2;String s7 = s1 + s2;System.out.println(s3 == s4); //trueSystem.out.println(s3 == s5);//falseSystem.out.println(s3 == s6);//falseSystem.out.println(s3 == s7);//falseSystem.out.println(s5 == s6);//falseSystem.out.println(s5 == s7);//falseSystem.out.println();String s8 = s5.intern(); //intern():返回的是字符串常量池中字面量的地址System.out.println(s3 == s8); //true}@Testpublic void test4(){final String s1 = "hello";final String s2 = "world";String s3 = "helloworld";String s4 = "hello" + "world";String s5 = s1 + "world"; // 通過查看字節碼文件發現調用了StringBuilder的toString() ---> new String()String s6 = "hello" + s2;String s7 = s1 + s2;System.out.println(s3 == s5); //trueSystem.out.println(s3 == s6); //trueSystem.out.println(s3 == s7); //true}@Testpublic void test5(){String s1 = "hello";String s2 = "world";String s3 = s1.concat(s2);String s4 = "hello".concat("world");String s5 = s1.concat("world");System.out.println(s3 == s4); //falseSystem.out.println(s3 == s5); //falseSystem.out.println(s4 == s5); //false}
}
class Person {String name;}
?練習3
public class StringMethod {@Testpublic void test1(){String s1 = new String();String s2 = new String("");String s3 = new String(new char[]{'a','b','c'});System.out.println(s3);}/*** String與常見的其他結構之間的轉換* 1.String與基本數據類型,包裝類之間的轉換(復習)**/@Testpublic void test2(){int num = 10;//基本數據類型 ---> String//方式1:String s1 = num + "";//方式2:String s2 = String.valueOf(num);//String ---> 基本數據類型:調用包裝類的parseXxx(String str)String s3 = "123";int i1 = Integer.parseInt(s1);}//String與char[]之間的轉換@Testpublic void test3(){String str = "hello";//String ---> char[]:調用String的toCharArray()char[] arr = str.toCharArray();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}//char[] ---> String:調用String的構造器String str1 = new String(arr);System.out.println(str1); //hello}//String與byte[]之間的轉換(難度)/*** 在utf-8字符集中,一個漢字占用3個字節,一個字母占用1個字節* 在gbk字符集中,一個漢字占用2個字節,一個字母占用1個字節* utf-8或gbk都向下兼容了ascii碼* 編碼與解碼:* 編碼:String ---> 字節或字節數組* 解碼:字節或字節數組 ---> String* 要求:解碼時使用的字符集必須與編碼時使用的字符集一致!不一致,就會亂碼*/@Testpublic void test4() throws UnsupportedEncodingException {String str = new String("abc中國");//String ---> byte[]:調用String的getBytes()byte[] arr = str.getBytes();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}System.out.println();//getBytes(String charsetName):使用指定的字符集byte[] arr1 = str.getBytes("gbk");for (int i = 0; i < arr1.length; i++) {System.out.println(arr1[i]);}//byte[] ---> StringString str1 = new String(arr); //使用默認的字符集:utf-8System.out.println(str1);// String str2 = new String(arr, "utf-8"); //顯式的指明解碼的字符集:utf-8
// System.out.println(str2);//亂碼
// String str3 = new String(arr, "gbk"); //顯式的指明解碼的字符集: gbk
// System.out.println(str3);String str4 = new String(arr1, "gbk");System.out.println(str4);}
}
?練習4
public class StringMethodTest1 {
// 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):比較兩個字符串的大小@Testpublic void test1(){String s1 = "";String s2 = new String();String s3 = new String("");System.out.println(s1.isEmpty()); //trueSystem.out.println(s2.isEmpty()); //trueSystem.out.println(s3.isEmpty()); //true
// String s4 = null;
// System.out.println(s4.isEmpty()); //包空指針異常String s5 = "hello";System.out.println(s5.length()); //5}@Testpublic void test2(){String s1 = "hello";String s2 = "hello";System.out.println(s1.equals(s2));System.out.println(s1.equalsIgnoreCase(s2));String s3 = "abcd";String s4 = "adef";System.out.println(s3.compareTo(s4));String s5 = "abcd";String s6 = "aBcd";System.out.println(s5.compareTo(s6));System.out.println(s5.compareToIgnoreCase(s6));String s7 = "張ab";String s8 = "李cd";System.out.println(s7.compareTo(s8));String s9 = " he llo ";System.out.println("***" + s9.trim() + "****"); //***he llo****}/*** boolean contains(CharSequence s):當且僅當此字符串包含指定的 char 值序列* 時,返回 true* int indexOf(String str):返回指定子字符串在此字符串中第一次出現處的索引* int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出* 現處的索引,從指定的索引開始* int lastIndexOf(String str):返回指定子字符串在此字符串中最右邊出現處的索引* int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后* 一次出現處的索引,從指定的索引開始反向搜索* 注:indexOf和lastIndexOf方法如果未找到都是返回-1*/@Testpublic void test3(){String s1 = "教育尚硅谷教育";System.out.println(s1.contains("硅谷"));System.out.println(s1.indexOf("教育"));System.out.println(s1.indexOf("教育", 1));System.out.println(s1.lastIndexOf("教育",4));}// String substring(int beginIndex):返回一個新的字符串,它是此字符串的從beginIndex開始截取到最后的一個子字符串。// String substring(int beginIndex, int endIndex) :返回一個新字符串,它是此字符串從beginIndex開始截取到endIndex(不包含)的一個子字符串。@Testpublic void test4(){String s1 = "教育尚硅谷教育";System.out.println(s1.substring(2));System.out.println(s1.substring(2,5));//[2,5)}/*** 18)char charAt(index):返回[index]位置的字符* (19)char[] tocharArray():將此字符串轉換為一個新的字符數組返回* (20)static string valueof(char[] data):返回指定數組中表示該字符序列的 String* (21)static String valueof(char[] data,int offset,int count): 返回指定數組中表示該字符序列的 string* (22)static string copyValue0f(char[] data): 返回指定數組中表示該字符序列的 string* (23)static string copyValue0f(char[] data, int ofset,int count):返回指定數組中表示該字符序列的 string*//*** (24)boolean startswith(xx):測試此字符串是否以指定的前綴開始* (25)boolean startswith(string prefix,int toffset):測試此字符串從指定索引開始的子字符串是否以指定前綴開始* (26)boolean endswith(xx):測試此字符串是否以指定的后綴結束*/@Testpublic void test5(){String s1 = "教育尚硅谷教育";System.out.println(s1.charAt(2));String s2 = String.valueOf(new char[]{'a','b','c'});String s3 = String.copyValueOf(new char[]{'a','b','c'});System.out.println(s2);System.out.println(s3);System.out.println(s2 == s3);System.out.println(s1.startsWith("教育a"));System.out.println(s1.startsWith("教育",5));}/*** (27)String replace(char oldchar, char newchar):返回一個新的字符串,它是通過用 newchar 替換此字符串中出* 現的所有 oldchar 得到的。 不支持正則。* (28)string replace(charSequence target, charSequence replacement):使用指定的字面值替換序列替換此字符串所有匹配字面值目標序列的子字符串。* (29)String replaceAll(string regex,string replacement):使用給定的replacement 替換此字符串所有匹配給定的正則表達式的子字符串。* (30)String replaceFirst(String regex,string replacement):使用給定的 replacement 替換此字符串匹配給定的正則表達式的第一個子字符串。*/@Testpublic void test6(){String s1 = "hello";String s2 = s1.replace('l','w');System.out.println(s1); //helloSystem.out.println(s2); //hewwoString s3 = s1.replace("ll","wwww");System.out.println(s3); //hewwwwo}
}
?練習5
/*** ClassName: StringTest* Package: com.atguigu01.string.exer1* Description:* //考查:方法參數的值傳遞機制、String的不可變性* @Author: lwfstart* @Create 2025-03-29 13:27* @Version: 1.0*/
public class StringTest {String str = "good";char[] ch = {'t','e','s','t'};public void change(String str,char ch[]){str = "test ok";ch[0] = 'b';}public static void main(String[] args) {StringTest ex = new StringTest();ex.change(ex.str,ex.ch);System.out.println(ex.str); // goodSystem.out.println(ex.ch); // best}
}
練習6
?
算法練習: 題目1:模擬一個trim方法,去除字符串兩端的空格。 題目2:將一個字符串進行反轉。將字符串中指定部分進行反轉。 比如"abcdefg"反轉為"abfedcg"題目3:獲取一個字符串在另一個字符串中出現的次致 比如:獲取"ab"在"abkkcadkabkebfkabkskab"中出現的次數題目4:獲取兩個字符串中最大相同子串。比如:str1 = "abcwerthelloyuiodef";str2 ="cvhellobnm" 提示:將短的那個串進行長度依次遞減的子串與較長的串比較。題目5:對字符串中字符進行自然順序排序。提示:1)字符串變成字符數組。2)對數組排序,選擇,冒泡,Arrays.sort();3)將排序后的數組變成字符串
代碼:
public class StringTest {/*** 題目2:將一個字符串進行反轉。將字符串中指定部分進行反轉。* 比如"abcdefg"反轉為"abfedcg"*/@Testpublic void test(){String s = "abcdefg";String s1 = reverse(s,2,5);String s2 = reverse(s,2,5);System.out.println(s1);System.out.println(s2);}/*** 方式1:將String轉為char[],針對char[]數組進行相應位置的反轉,反轉以后將char[]轉為String*/public String reverse(String str, int fromIndex, int toIndex) {//char[] arr = str.toCharArray();//for (int i = fromIndex,j=toIndex; i < j; i++,j--) {char temp = arr[i];arr[i] = arr[j];arr[j] = temp;}//return new String(arr);}public String reverse2(String str,int fromIndex,int toIndex){//獲取str的第1部分String finalStr = str.substring(0,fromIndex); //ab//拼接上第2部分for(int i = toIndex; i >= fromIndex;i--){finalStr += str.charAt(i);} //abfedc//拼接上第3部分finalStr += str.substring(toIndex +1);return finalStr;}/*** 題目3:獲取一個字符串在另一個字符串中出現的次致* 比如:獲取"ab"在"abkkcadkabkebfkabkskab"中出現的次數*//*** 判斷subStr在str中出現的次數* @param str* @param subStr* @return 返回次數*/public int getSubStringCount(String str,String subStr){int count = 0; //記錄出現的次數int index = str.indexOf(subStr);while(index >= 0){count++;index = str.indexOf(subStr,index+subStr.length());}return count;}@Testpublic void test2(){String subStr = "ab";String str = "abkkcadkabkebfkabkskab";int count = getSubStringCount(str,subStr);System.out.println(count);}
}
?算法代碼:
/** 1.模擬一個trim方法,去除字符串兩端的空格。* * 2.將一個字符串進行反轉。將字符串中指定部分進行反轉。比如將“abcdefg”反轉為”abfedcg”* * 3.獲取一個字符串在另一個字符串中出現的次數。比如:獲取“ab”在 “cdabkkcadkabkebfkabkskab” 中出現的次數4.獲取兩個字符串中最大相同子串。比如:str1 = "abcwerthelloyuiodef“;str2 = "cvhellobnm"//10提示:將短的那個串進行長度依次遞減的子串與較長 的串比較。5.對字符串中字符進行自然順序排序。"abcwerthelloyuiodef"
提示:
1)字符串變成字符數組。
2)對數組排序,選擇,冒泡,Arrays.sort(str.toCharArray());
3)將排序后的數組變成字符串。*/
public class StringExer {// 第1題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題// 方式一:public String reverse1(String str, int start, int end) {// start:2,end:5if (str != null) {// 1.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 str, int start, int end) {// 1.String newStr = str.substring(0, start);// ab// 2.for (int i = end; i >= start; i--) {newStr += str.charAt(i);} // abfedc// 3.newStr += str.substring(end + 1);return newStr;}// 方式三:推薦 (相較于方式二做的改進)public String reverse3(String str, int start, int end) {// ArrayList list = new ArrayList(80);// 1.StringBuffer s = new StringBuffer(str.length());// 2.s.append(str.substring(0, start));// ab// 3.for (int i = end; i >= start; i--) {s.append(str.charAt(i));}// 4.s.append(str.substring(end + 1));// 5.return s.toString();}@Testpublic void testReverse() {String str = "abcdefg";String str1 = reverse3(str, 2, 5);System.out.println(str1);// abfedcg}// 第3題// 判斷str2在str1中出現的次數public int getCount(String mainStr, String subStr) {if (mainStr.length() >= subStr.length()) {int count = 0;int index = 0;// 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;}}@Testpublic void testGetCount() {String str1 = "cdabkkcadkabkebfkabkskab";String str2 = "ab";int count = getCount(str1, str2);System.out.println(count);}@Testpublic void testMyTrim() {String str = " a ";// str = " ";String newStr = myTrim(str);System.out.println("---" + newStr + "---");}// 第4題// 如果只存在一個最大長度的相同子串public String getMaxSameSubString(String str1, String str2) {if (str1 != null && str2 != null) {String maxStr = (str1.length() > str2.length()) ? str1 : str2;String minStr = (str1.length() > str2.length()) ? str2 : str1;int len = minStr.length();for (int i = 0; i < len; i++) {// 0 1 2 3 4 此層循環決定要去幾個字符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[] getMaxSameSubString1(String str1, String str2) {if (str1 != null && str2 != null) {StringBuffer sBuffer = new StringBuffer();String maxString = (str1.length() > str2.length()) ? str1 : str2;String minString = (str1.length() > str2.length()) ? str2 : str1;int len = minString.length();for (int i = 0; i < len; i++) {for (int x = 0, y = len - i; y <= len; x++, y++) {String subString = minString.substring(x, y);if (maxString.contains(subString)) {sBuffer.append(subString + ",");}}System.out.println(sBuffer);if (sBuffer.length() != 0) {break;}}String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");return split;}return null;}// 如果存在多個長度相同的最大相同子串:使用ArrayList
// public List<String> getMaxSameSubString1(String str1, String str2) {
// if (str1 != null && str2 != null) {
// List<String> list = new ArrayList<String>();
// String maxString = (str1.length() > str2.length()) ? str1 : str2;
// String minString = (str1.length() > str2.length()) ? str2 : str1;
//
// int len = minString.length();
// for (int i = 0; i < len; i++) {
// for (int x = 0, y = len - i; y <= len; x++, y++) {
// String subString = minString.substring(x, y);
// if (maxString.contains(subString)) {
// list.add(subString);
// }
// }
// if (list.size() != 0) {
// break;
// }
// }
// return list;
// }
//
// return null;
// }@Testpublic void testGetMaxSameSubString() {String str1 = "abcwerthelloyuiodef";String str2 = "cvhellobnmiodef";String[] strs = getMaxSameSubString1(str1, str2);System.out.println(Arrays.toString(strs));}// 第5題@Testpublic void testSort() {String str = "abcwerthelloyuiodef";char[] arr = str.toCharArray();Arrays.sort(arr);String newStr = new String(arr);System.out.println(newStr);}
}
模擬用戶登錄
案例:模擬用戶登錄 (1)定義用戶類,屬性為用戶名和密碼,提供相關的getter和setter方法,構造器,toString()。(2)使用數組存儲多個用戶對象。(3)錄入用戶和密碼,對比用戶信息,匹配成功登錄成功,否則登錄失敗。> 登錄失敗時,當用戶名錯誤,提示沒有該用戶。> 登錄失敗時,當密碼錯誤時,提示密碼有誤。效果如圖所示:
練習:
UserTest
public class UserTest {public static void main(String[] args) {//1.創建數組,并初始化幾個User對象User[] arr = new User[3];arr[0] = new User("Tom", "8888");arr[1] = new User("songhk", "123");arr[2] = new User("Jerry","6666");System.out.println("庫中的用戶有:");for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}//2.實例化Scanner,獲取輸入的用戶名和密碼Scanner scan = new Scanner(System.in);System.out.println("請輸入用戶名:");String userName = scan.next();System.out.println("請輸入密碼:");String password = scan.next();//3.遍歷數組元素,匹配用戶名和密碼boolean isFlag = true;for (int i = 0; i < arr.length; i++) {if(arr[i].getName().equals(userName)) { //存在此用戶名isFlag = false;if(arr[i].getPassword().equals(password)) {System.out.println("登錄成功" + userName);}else {System.out.println("密碼有誤");}break;}}if(isFlag) {System.out.println("沒有該用戶");}scan.close();}
}User
public class User {private String name; //姓名private String password; //密碼public User() {}public User(String name, String password) {this.name = name;this.password = password;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return name + "-" + password;}
}
String與基本數據類型轉換
String與字節數組轉換
StringBuffer類
總結:
1.三個類的對比:String、stringBuffer、StringBuilder > String:不可變的字符序列;底層使用char[](jdk8及之前),底層使用byte[](jdk9及之后) > StringBuffer:可變的字符序列;JDK1.0聲明,線程安全的,效率低;底層使用byte[](jdk9及之后) > StringBuilder: 可變的字符序列;JDK5.0聲明,線程不安全的,效率高;底層使用byte[](jdk9及之后)2.StringBuffer/stringBuilder的可變性分析(源碼分析): 回顧: String s1 = new String();//char[] value = new char[0]; String s2 = new String("abc");// char[] value = new char[]{'a','b','c'}; 針對于StringBuilder來說: 內部的屬性有:char[] value;//存儲字符序列int count;//實際存儲的字符的個數StringBuilder sBuffer1 = new StringBuilder();//char[] value = new char[16]; StringBuilder sBuffer1 = new stringBuilder("abc"): //char[] value = new char[16 + "abc".length()]; sBuffer1.append("ac");//value[0]='a';value[1]='c'; sBuffer1.append("b");//value[2]='b'; ...不斷的添加,一旦count要超過value.length時,就需要擴容:默認擴容為原有容量的2倍+2。 并將原有value數組中的元素復制到新的數組中, 3.源碼啟示: > 如果開發中需要頻繁的針對于字符串進行增、刪、改等操作,建議使用stringBuffer或stringBuilder替換String. 因為使用string效率低。 > 如果開發中,不涉及到線程安全問題,建議使用StringBuilder替換StringBuffer > 如果開發中大體確定要操作的字符的個數,建議使用帶int capacity參數的構造器。因為可以避免底層多次擴容操作,性能更高 4.StringBuffer和StringBuilder中的常用方法5.對比三者的執行效率 效率從高到低排列: StringBuilder > StringBuffer > String
代碼:
public class StringBufferBuilderTest {/*** *(1)StringBuffer append(xx):提供了很多的append()方法,用于進行字符串追加的方式拼接* (2)StringBuffer delete(int start, int end): 刪除[start,end)之間字符* (3)StringBuffer deleteCharAt(int index):刪除[index]位置字符* (4)StringBuffer replace(int start, int end,string str):替換[start,end)范圍的字符序列為str* (5)void setCharAt(int index,char c):替換[index]位置字符* (6)char charAt(int index):查找指定index位置上的字符* (7)StringBuffer insert(int index,xx):在[index]位置插入xx* (8)int length():返回存儲的字符數據的長度* (9)StringBuffer reverse():反轉*/@Testpublic void test1(){StringBuilder sBuilder = new StringBuilder();sBuilder.append("abc").append("123").append("def"); //方法鏈的調用System.out.println(sBuilder); //abc123def}@Testpublic void test2(){StringBuilder sBuilder = new StringBuilder("hello");sBuilder.insert(2,1);sBuilder.insert(2, "abc");System.out.println(sBuilder);StringBuilder sBuilder1 = sBuilder.reverse();System.out.println(sBuilder1);System.out.println(sBuilder == sBuilder1); //trueSystem.out.println(sBuilder.length()); //實際存儲的字符的個數}@Testpublic void test3(){StringBuilder sBuilder = new StringBuilder("hello");sBuilder.setLength(2);System.out.println(sBuilder);sBuilder.append("c");System.out.println(sBuilder);sBuilder.setLength(10);System.out.println(sBuilder);System.out.println(sBuilder.charAt(6)==0); //true}/*** 測試String、StringBuffer、StringBuilder在操作數據方面的效率**/@Testpublic void test4(){//初始設置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));}
}
面試題:
public class InterviewTest1 {public static void main(String[] args) {StringBuffer a = new StringBuffer("A");StringBuffer b = new StringBuffer("B");operate(a,b);System.out.println(a + "," + b); //ABx,B}//引用類型傳遞地址public static void operate(StringBuffer x, StringBuffer y) {x.append(y);y = x; //y指向的是地址,這個地址指向的是堆空間實際的對象,所以最后這個對象更改成了ABxy.append('x');} //a的地址給了x,x的地址給了y,y也指向了a所指向的地址,所以y的地址改變了,a的內容頁同樣會改變
}2
public class InterviewTest2 {public static void stringReplace(String text){//這個地方改變的是形參text = text.replace('j','i');}public static void bufferReplace(StringBuffer text){text.append("C");text = new StringBuffer("Hello"); //這個地方重新賦值了一個地址,所以后面的改變跟傳遞過來的那個地址沒有關系了text.append("World!");}public static void main(String[] args) {String textString = new String("java");StringBuffer textBuffer = new StringBuffer("java");stringReplace(textString); //java 傳遞過去的是一個地址,但是體現了String的不可變性bufferReplace(textBuffer); //javaCSystem.out.println(textString + textBuffer); //javajavaC}
}3
public class InterviewTest3 {public static void change(String s,StringBuffer sb){s = "aaaa";sb.setLength(0);sb.append("aaaa");}public static void main(String[] args) {String s = "bbbb";StringBuffer sb = new StringBuffer("bbbb");change(s,sb);System.out.println(s+sb); //bbbbaaaa}
}4
public class InterviewTest4 {public static void main(String[] args) {String str = null;StringBuffer sb = new StringBuffer();sb.append(str);System.out.println(sb.length()); //0 4 16System.out.println(sb); //"null"StringBuffer sb1 = new StringBuffer(str);System.out.println(sb1);//"" "null" null NullPointerException 空指針異常}
}
JDK8之前日期時間API
相關代碼:?
public class DateTimeTest {/*** Date類的使用* |--java.util.Date* >兩個構造器的使用* >兩個方法的使用 ① tostring() ② getTime()* |----java.sql.Date:對應著數據庫中的date類型*/@Testpublic void test1(){Date date1 = new Date(); //創建一個基于當前系統時間的Date的實例System.out.println(date1.toString());long milliTime = date1.getTime();System.out.println("對應的毫秒數為:" + milliTime); //1743247093560Date date2 = new Date(1743247093560L); //創建一個基于指定時間戳的Date的實例System.out.println(date2.toString());}@Testpublic void test2(){java.sql.Date date1 = new java.sql.Date(1743247093560L);System.out.println(date1.toString()); //2025-03-29System.out.println(date1.getTime()); //1743247093560}/*** SimpleDateFormat類:用于日期時間的格式化和解析* 格式化:日期 ---> 字符串* 解析:字符串 ---> 日期*/@Testpublic void test3() throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat();//格式化:日期 ---> 字符串Date date1 = new Date();String strDate = sdf.format(date1);System.out.println(strDate); //25-3-29 下午8:08//解析:字符串 ---> 日期Date date2 = sdf.parse("25-3-29 下午5:08");System.out.println(date2); //Sat Mar 29 17:08:00 CST 2025}@Testpublic void test4() throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化:日期 ---> 字符串Date date1 = new Date();String strDate = sdf.format(date1);System.out.println(strDate); //星期六, 29 三月 2025 20:19:39 +0800 ---> 2025-03-29 20:22:39//解析:字符串 ---> 日期Date date2 = sdf.parse("2025-03-29 20:22:39");System.out.println(date2); //Sat Mar 29 20:22:39 CST 2025
// 解析失敗,因為參數的字符串不滿足SimpleDateFormat可以識別的格式 DateFormat
// sdf.parse("2025-03-29 下午2:39");
// System.out.println(date2);}/*** Calender:日歷類* ① 實例化 由于Calendar是一個抽象類,所以我們需要創建其子類的實例,這里我們通過Calendar的靜態方法* getInstance()即可獲取* ② 常用方法:get(int field) / set(int field, xx) / add(int field, xx) / getTime() / setTime()*/@Testpublic void test5(){Calendar calendar = Calendar.getInstance();
// System.out.println(calendar.getClass());//測試方法System.out.println(calendar.get(Calendar.DAY_OF_MONTH));System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
// set(int field, xx)calendar.set(Calendar.DAY_OF_MONTH, 23);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//add(int field, xx)calendar.add(Calendar.DAY_OF_MONTH, 3);calendar.add(Calendar.DAY_OF_MONTH, -5);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//getTime():Calendar --> DateDate date = calendar.getTime();System.out.println(date);//setTime():使用指定Date重置CalendarDate date1 = new Date();calendar.setTime(date1);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));}
}
JDK8中新日期時間API
LocalDate、LocalTime、LocalDateTime
瞬時:Instant
格式化與解析日期或時間?
?其它API
?總結:
一、JDK8之前的API: 1.System類的currentTimeMillis() > 獲取當前時間對應的毫秒數,Long類型,時間戳 > 當前時間與1970年1月1日0時0分0秒之間的毫秒數 > 常用來計算時間差2.兩個Date類|--java.util.Date>兩個構造器的使用>兩個方法的使用 ① tostring() ② getTime()|----java.sql.Date:對應著數據庫中的date類型 3.SimpleDateFormat類 SimpleDateFormat類:用于日期時間的格式化和解析格式化:日期 ---> 字符串解析:字符串 ---> 日期4.Calendar類(日歷類):抽象類 Calender:日歷類① 實例化 由于Calendar是一個抽象類,所以我們需要創建其子類的實例,這里我們通過Calendar的靜態方法getInstance()即可獲取② 常用方法:get(int field) / set(int field, xx) / add(int field, xx) / getTime() / setTime()二、JDK8中的API: 1.LocalDate,LocalTime,LocalDateTime ---> 類似于Calendar > 實例化:now() / of(xxx,xx,xx) > 方法:get() / withXxx() / plusXxx() / minusXxx()’2. Instant:瞬時 --->類似于Date > 實例化:now() / ofEpochMilLi() > 方法:toEpochMilli()3. DateTimeFormatter --> 類似于SimpleDateFormat 用于格式化和解析LocalDate,LocalTime,LocalDateTime
代碼:
練習: 如何將一個java.util.Date的實例轉換為java.sql.Date的實例拓展: 將控制臺獲取的年月日(比如:2022-12-13)的字符串數據,保存在數據庫中。 (簡化為得到java.sql.Date的對象,此對象對應的時間為2022-12-13)。public class Exer01 {/*** 練習:* 如何將一個java.util.Date的實例轉換為java.sql.Date的實例*/@Testpublic void test1(){Date date1 = new Date();//錯誤的: // java.sql.Date date2 = (java.sql.Date) date1; // System.out.println(date2);//正確的:java.sql.Date date2 = new java.sql.Date(date1.getTime());System.out.println(date2);}/*** 拓展:* 將控制臺獲取的年月日(比如:2022-12-13)的字符串數據,保存在數據庫中。* (簡化為得到java.sql.Date的對象,此對象對應的時間為2022-12-13)。** 字符串 ---> java.util.Date ---> java.sql.Date*/@Testpublic void test2() throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String pattern = "2022-12-13";//得到java.util.DateDate date1 = sdf.parse(pattern);//轉換為java.sql.Datejava.sql.Date date2 = new java.sql.Date(date1.getTime());System.out.println(date2); //2022-12-13} }
?代碼2:
案例:百天推算 使用Calendar獲取當前時間,把這個時間設置為你的生日,再獲取你的百天(出生后100天)日期。 使用LocalDateTime獲取當前時間,把這個時間設置為你的生日,再獲取你的百天(出生后100天)日期。public class Exer02 {/*** 使用Calendar獲取當前時間,把這個時間設置為你的生日,再獲取你的百天(出生后100天)日期。*/@Testpublic void test1(){Calendar calendar = Calendar.getInstance();Date date = calendar.getTime();System.out.println("你的生日為:" + date);calendar.add(Calendar.DAY_OF_YEAR,100);Date newDate = calendar.getTime();System.out.println("100天以后是:" + newDate);}/*** 使用LocalDateTime獲取當前時間,把這個時間設置為你的生日,再獲取你的百天(出生后100天)日期。*/@Testpublic void test2(){LocalDateTime localDateTime = LocalDateTime.now();System.out.println("你的生日為:" + localDateTime);LocalDateTime localDateTime1 = localDateTime.plusDays(100);System.out.println("100天以后是" + localDateTime1);} }
代碼3:
?
public class DateTimeTest {/*** 可變性:像日期和時間這樣的類應該是不可變的。* 偏移性:Date中的年份是從1900開始的,而月份都從0開始。* 格式化:格式化只對Date有用,Calendar則不行。* 此外,它們也不是線程安全的;不能處理閏秒等。*/@Testpublic void test1(){String s1 = "hello";String s2 = s1.replace('l','w'); //String的不可變性System.out.println(s2);//體會Calendar的可變性Calendar calendar = Calendar.getInstance();calendar.set(Calendar.DAY_OF_MONTH,23);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));}@Testpublic void test2(){// 偏移性:Date中的年份是從1900開始的,而月份都從0開始。Date date = new Date(2022,11,14);System.out.println(date);}/*** JDK8的api:LocalDate \ LocalTime \ LocalDateTime*/@Testpublic void test3(){//now():獲取當前日期和時間對應的實例LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate); //2025-03-29System.out.println(localTime); //21:56:26.981System.out.println(localDateTime); //2025-03-29T21:56:26.981//of():獲取指定的日期、時間對應的實例LocalDate localDate1 = LocalDate.of(2021, 5, 23);LocalDateTime localDateTime1 = LocalDateTime.of(2022,12,5,11,23,45);System.out.println(localDate1);System.out.println(localDateTime1);//getXXX()LocalDateTime localDateTime2 = LocalDateTime.now();System.out.println(localDateTime2.getDayOfMonth());//體現不可變性
// withXxx()LocalDateTime localDateTime3 = localDateTime2.withDayOfMonth(15);System.out.println(localDateTime2); //2025-03-29T22:05:16.169System.out.println(localDateTime3); //2025-03-15T22:05:16.169LocalDateTime localDateTime4 = localDateTime2.plusDays(5);System.out.println(localDateTime2); //2025-03-29T22:05:16.169System.out.println(localDateTime4); //2025-04-03T22:08:00.499}/*** JDK8的api:Instant*/@Testpublic void test4(){//now():Instant instant = Instant.now();System.out.println(instant); //2025-03-29T14:15:09.671Z//了解:OffsetDateTime instance1 = instant.atOffset(ZoneOffset.ofHours(8));System.out.println(instance1); //2025-03-29T22:17:40.782+08:00Instant instance2 = Instant.ofEpochMilli(24123123312L);System.out.println(instance2); //1970-10-07T04:52:03.312Zlong milliTime = instant.toEpochMilli();System.out.println(milliTime); //1743258123429System.out.println(new Date().getTime()); //1743258123470}/*** JDK8的api: DateTimeFormatter*/@Testpublic void test5(){//自定義格式:如:ofPattern("yyyy-MM-dd hh:mm:ss")DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm:ss");//格式化:日期、時間-->字符串LocalDateTime localDateTime = LocalDateTime.now();String strDateTime = dateTimeFormatter.format(localDateTime);System.out.println(strDateTime); //2025/03/29 10:39:16//解析:字符串 ---> 日期、時間TemporalAccessor temporalAccessor = dateTimeFormatter.parse("2025/03/29 10:39:16");
// LocalDateTime.from(temporalAccessor);
// LocalDateTime localDateTime1 = LocalDateTime.from(temporalAccessor);
// System.out.println(localDateTime1); //}
}
Java比較器
?總結:
1.實現對象的排序,可以考慮兩種方法: 自然排序、定制排序 2.方式一:實現Comparable接口的方式 實現步驟: ① 具體的類A實現Comparable接口 ② 重寫Comparable接口中的compareTo(0bject obj)方法,在此方法中指明比較類A的對象的大小的標準 ③ 創建類A的多個實例,進行大小的比較或排序。3.方式二: 實現步驟: ① 創建一個實現了Comparator接口的實現類A ② 實現類A要求重寫Comparator接口中的抽象方法compare(0bject o1,0bject o2),在此方法中指明要比較大小的對象的大小關系。(比如,string類、Product類) ③ 創建此實現類A的對象,并將此對象傳入到相關方法的參數位置即可。(比如:Arrays.sort(.,類A的實例))4.對比兩種方式: 角度一:自然排序:單一的,唯一的定制排序:靈活的,多樣的 角度二:自然排序:一勞永逸的定制排序:臨時的 角度三:細節自然排序:對應的接口是Comparable,對應的抽象方法compareTo(Object obj)定制排序:對應的接口是Comparator,對應的抽象方法compare(Object obj1,Object obj2)
相關代碼:
Product
public class Product implements Comparable{ //商品類private String name; //商品名稱private double price; //價格public Product() {}public Product(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;}@Overridepublic String toString() {return "Product{" +"name='" + name + '\'' +", price=" + price +'}';}/*** 當前的類需要實現Comparable中的抽象方法:compareTo(Object o)* 在此方法中,指明如何判斷當前類的對象的大小,比如:按照價格的高低進行大小的比較(或從低到高排序)** 如果返回值是正數,當前對象大* 如果返回值是負數,當前對象小* 如果返回值是0,一樣大*/
// @Override
// public int compareTo(Object o){
// if(o == this){
// return 0;
// }
// if(o instanceof Product){
// Product p = (Product)o;
// return Double.compare(this.price,p.price);
// }
// //手動拋出一個異常類的對象
// throw new RuntimeException("類型不匹配");
// }//比較的標準:先比較價格,進行名字的比較,(從小到大)@Overridepublic int compareTo(Object o){if(o == this){return 0;}if(o instanceof Product){Product p = (Product)o;int value = Double.compare(this.price, p.price);if(value != 0){return -value;}return -this.name.compareTo(p.name);}//手動拋出一個異常類的對象throw new RuntimeException("類型不匹配");}
}
?
ComparableTest
public class ComparableTest {@Testpublic void test1(){/*** Jack* Jerry* Lucy* Rose* Tom* Tony*/String[] arr = new String[]{"Tom","Jerry","Tony","Rose","Jack","Lucy"};Arrays.sort(arr);//排序后,遍歷for(int i = 0; i < arr.length; i++){System.out.println(arr[i]);}}@Testpublic void test2(){Product[] arr = new Product[5];arr[0] = new Product("HuaweiMate50Pro", 6299);arr[1] = new Product("Xiaomi13pro", 4999);arr[2] = new Product("VivoX90pro", 5999);arr[3] = new Product("Iphone14ProMax", 9999);arr[4] = new Product("HonorMagic4", 6299);Arrays.sort(arr);for(int i = 0; i < arr.length; i++){System.out.println(arr[i]);}}@Testpublic void test3(){Product p1 = new Product("HuaweiMate50Pro", 6999);Product p2 = new Product("VivoX90pro", 5999);int compare = p1.compareTo(p2);if(compare > 0) {System.out.println("p1大");}else if(compare < 0){System.out.println("p2大");}else{System.out.println("p1hep2一樣大");}}
}
?
public class ComparatorTest {@Testpublic void test1(){Product[] arr = new Product[5];arr[0] = new Product("HuaweiMate50Pro", 6299);arr[1] = new Product("Xiaomi13pro", 4999);arr[2] = new Product("VivoX90pro", 5999);arr[3] = new Product("Iphone14ProMax", 9999);arr[4] = new Product("HonorMagic4", 6299);//創建一個實現了Comparator接口的實現類的對象Comparator comparator = new Comparator(){//如何判斷兩個對象o1,o2的大小,其標準就是此方法的方法體要編寫的邏輯//按照價格從高到低排序@Overridepublic int compare(Object o1, Object o2) {if(o1 instanceof Product && o2 instanceof Product){Product p1 = (Product)o1;Product p2 = (Product)o2;return -Double.compare(p1.getPrice(),p2.getPrice());}throw new RuntimeException("類型不匹配");}};Comparator comparator1 = new Comparator(){//如何判斷兩個對象o1,o2的大小,其標準就是此方法的方法體要編寫的邏輯//比如:按照name從低到高排序@Overridepublic int compare(Object o1, Object o2) {if(o1 instanceof Product && o2 instanceof Product){Product p1 = (Product)o1;Product p2 = (Product)o2;return p1.getName().compareTo(p2.getName());}throw new RuntimeException("類型不匹配");}};Arrays.sort(arr,comparator1);for(int i = 0; i < arr.length; i++){System.out.println(arr[i]);}}@Testpublic void test2(){String[] arr = new String[]{"Tom","Jerry","Tony","Rose","Jack","Lucy"};Arrays.sort(arr,new Comparator(){@Overridepublic 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("類型不匹配");}});//排序后,遍歷for(int i = 0; i < arr.length; i++){System.out.println(arr[i]);}}
}
System類
Math類
BigInteger類
BigDecimal類
總結:
1.System類 > 屬性:out、in、err > 方法:currentTimeMillis() / gc() / exit(int status) / getProperty(String property)2. Runtime類 > 對應著Java進程的內存使用的運行時環境,是單例的3.Math類 > 凡是與數學運算相關的操作,大家可以在此類中找相關的方法即可4.BigInteger類和BigDecimal類BigInteger:可以表示任意長度的整數BigDecimal:可以表示任意精度的浮點數5. Random類 > 獲取指定范圍的隨機整數:nextInt(int bound)
相關代碼:
public class OtherAPITest {@Testpublic 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);}@Testpublic void test2(){Runtime runtime = Runtime.getRuntime();long initialMemory = runtime.totalMemory();//獲取虛擬機初始化時堆內存總量long maxMemory = runtime.maxMemory();//獲取虛擬機最大堆內存總量String str ="";//模擬占用內存for(int i=0;i<10000;i++){str += 1;}long freeMemory = runtime.freeMemory();//獲取空閑堆內存總量System.out.println("總內存:" + initialMemory / 1024 / 1024 * 64 +"MB");System.out.println("總內存:"+ maxMemory / 1024 / 1024 * 4 + "MB");System.out.println("空閑內存:"+freeMemory /1024 / 1024 +"MB");System.out.println("已用內存:"+(initialMemory-freeMemory)/ 1024 / 1024 + "MB");}@Testpublic void test3(){//四舍五入,往大了的方向靠//技巧:floor(x + 0.5)System.out.println(Math.round(12.3)); //12System.out.println(Math.round(12.5)); //13System.out.println(Math.round(-12.3)); //-12System.out.println(Math.round(-12.6)); //-13System.out.println(Math.round(-12.5)); //-12}@Testpublic void test4(){
// long bigNum = 123456789123456789123456789L;BigInteger b1 = new BigInteger( "12345678912345678912345678");BigInteger b2 = new BigInteger( "78923456789123456789123456789");//System.out.println("和:"+(b1+b2));//錯誤的,無法直接使用+進行求和System.out.println("和:"+ b1.add(b2));System.out.println("減:"+ b1.subtract(b2));System.out.println("乘:"+ b1.multiply(b2));System.out.println("除:"+ b2.divide(b1));System.out.println("余:"+ b2.remainder(b1));}@Testpublic void test5(){BigInteger bi =new BigInteger( "12433241123");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, 15,BigDecimal.ROUND_HALF_UP));}@Testpublic void test6(){Random random = new Random();int i = random.nextInt();System.out.println(i);int j = random.nextInt(10); //隨機獲取[0,10)范圍的整數System.out.println(j);}
}