StringBuffer和StringBulider和String辨析
- 基本概念
StringBuffer | StringBulider | String |
---|---|---|
可變字符序列, 字符緩衝區 | 可變字符序列, 字符緩衝區 | 字符串 |
- 特點與區別
StringBuffer | StringBulider | String |
---|---|---|
線程安全 | 線程不安全 | - |
運行效率低 | 運行效率高 | - |
可變字符序列 | 可變字符序列 | 不可變的字符序列 |
-
StringBuffer和String使用特點
-
對StringBuffer對象進行追加等一系操作,不會創建新的地址
-
對String 對象進行一些列操作時會創建新的(地址)
public class Demo01{ public static void main(String[] args){ String s01="abc"; String s02="a"+"b"+"c"; String s03="ab"; String s04=s03+"c"; /* 對象比較 S01==S02!=S04 S04因爲有s03(String[的加])的運算,重新賦予對象地址值 */ } }
自動裝箱和自動拆箱
- 自動裝箱: 把基本數據類型轉換爲包裝類型
- Integer i01 = new Integer(10);// 自動裝箱
- 自動拆箱: 把包裝類型轉換成基本數據類型
- int i = i01;// 自動拆箱
獲取獲取毫秒值(3種)–Day12
- 使用system方法
- System.currentTimeMillis();
- 使用date方法
- Date d=new Date();
- d.getTime()
- 使用Calendar
- Calendar now =Calendar.getIntance();
- now.getTime().getTime();
獲取隨機數
-
Math 的 random 範圍[0,1)–>湊數
- 例3: 取隨機數33~53==》[0,1)x21 -> [0,21)==》 [0,1) x 21+33 -> [33,54)
- 返回值類型double==Math.floor(Math.random()*21+33);
- 注:java的方法的使用範圍一般顧頭不顧尾
-
Random 方法 產生一個(0,參數](不包括參數)之內的隨機整數
-
Random r = new Random();
-
r.nextInt(100)//[0~100)隨機數
-
注:
-
1、Random 產生的是僞數,相同的種子參數的隨機數相同
-
同一個Random(種子)生成的對象,獲取的數據數相同
-
Random ran1 = new Random(100); Random ran2 = new Random(100); for(int i = 0;i<5;i++){ int a = ran1.nextInt(50); //Random.nextInt決定範圍 // == 隨機數給予的值[0,1)*50 //因ran1和ran2 種子數一致,隨機數的結果一致 //ps:就像植物一樣,同一品種的種子,最後長大後爲同一物種 int b = ran2.nextInt(50); System.out.print("ran1的值"+a); System.out.print("ran2的值"+b); System.out.println(); } //運行結果 // ran1的值15 ran2的值15 // ran1的值0 ran2的值0 // ran1的值24 ran2的值24 // ran1的值38 ran2的值38 // ran1的值41 ran2的值41
-
-
-
使用隨機函數時,調用空的構造函數,這樣可生成不重複的隨機數
- Random r=new Random();
-
System
- 常用的方法
- public static void gc() : 暗示垃圾回收器運行
- public static void exit(int status) : 虛擬機退出
- public static long currentTimeMillis() : 獲取當前時間的毫秒值
SimpleDateFormat(非常重要)
- Date==>String
- Date date = new Date();// 創建日期對象
- SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);// 創建格式化工具對象
- String time = sdf.format(date);// 格式化日期得到時間字符串
- String ==>Date
- SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);// 格式化日期得到時間字符串
- Date date = sdf.parse(“2019-10-12”);//格式化時間字符串得到日期-try-catch(異常處理)
正則表達式
- 概述
- 正則表達式(對象)能夠快速的匹配字符串
正則表達式的使用(Pattern 和Match)
- Pattern (匹配規制)
- Pattern p = Pattern.compile(“正則表達式”);
- Match(匹配函數)
- Matcher m = p.matcher(“匹配的串”);
- m.find()與m.group()
- m.find()【嘗試找到符合匹配模式的成功序列,並指向的成功的下一個子序列】
- m.group()【返回與上一個匹配成功的子序列】