一. StringBuffer
-
定義
- 線程安全的可變字符序列, 一個類似于String的字符緩沖區(qū), 我們可以將StringBuffer看作是一個高級的String
- StringBuffer和String的區(qū)別
- String是一個不可變的字符序列
- StringBuffer是一個可變的字符序列
-
構(gòu)造方法
- public StringBuffer():無參構(gòu)造方法 默認(rèn)容量是16
- public StringBuffer(int capacity):指定容量的字符串緩沖區(qū)對象
- public StringBuffer(String str):指定字符串內(nèi)容的字符串緩沖區(qū)對象
- 擴(kuò)容公式: 原容量<< 1 + 2
-
常用方法
-
容量和長度
public int capacity() : 返回當(dāng)前容量 理論值(不掌握)
public int length() : 返回長度(字符數(shù)) 實際值
演示
public static void main(String[] args) { StringBuffer buffer = new StringBuffer(); //獲取容量 int capacity = buffer.capacity(); //獲取內(nèi)容的長度 int length = buffer.length(); System.out.println(capacity); System.out.println(length); }
-
添加
-
public StringBuffer append(String str)
- 可以把任意類型數(shù)據(jù)添加到字符串緩沖區(qū)里面,并返回字符串緩沖區(qū)本身
-
public StringBuffer insert(int offset,String str)
- 在指定位置把任意類型的數(shù)據(jù)插入到字符串緩沖區(qū)里面,并返回字符串緩沖區(qū)本身
- 演示
public static void main(String[] args) { StringBuffer buffer = new StringBuffer("abcd"); buffer.append("abbc"); System.out.println(buffer.toString());//結(jié)果:abcdabbc buffer.insert(2,"我愛你");//插入到指定位置 System.out.println(buffer.toString()); }
-
-
刪除
- public StringBuffer deleteCharAt(int index):
- 刪除指定位置的字符宪肖,并返回本身
- public StringBuffer delete(int start,int end):
- 刪除從指定位置開始指定位置結(jié)束的內(nèi)容蔗候,并返回本身
- 演示
public static void main(String[] args) { StringBuffer buffer = new StringBuffer("abcd"); buffer.deleteCharAt(1);//刪除角標(biāo)為1的值 System.out.println(buffer.toString());//結(jié)果:acd buffer.delete(1, 2); System.out.println(buffer.toString());//結(jié)果:ad }
- public StringBuffer deleteCharAt(int index):
-
替換和反轉(zhuǎn)
- public StringBuffer replace(int start,int end,String str)
- 從start開始到end用str替換
- public StringBuffer reverse()
- 字符串反轉(zhuǎn)
- 演示
public static void main(String[] args) { StringBuffer buffer = new StringBuffer("abcd"); //替換一部分內(nèi)容 buffer.replace(1, 3, "我愛你"); System.out.println(buffer.toString());//結(jié)果:a我愛你d //反轉(zhuǎn) buffer.reverse(); System.out.println(buffer.toString());//結(jié)果:d你愛我a }
- public StringBuffer replace(int start,int end,String str)
-
截取
- public String substring(int start)
- 從指定位置截取到末尾
- public String substring(int start,int end):
- 截取從指定位置開始到結(jié)束位置,包括開始位置绊含,不包括結(jié)束位置
- 注意: 返回值不再是StringBuffer本身,而是一個String
- 演示
public static void main(String[] args) { StringBuffer buffer = new StringBuffer("abcdefg"); //截取一部分,從某個角標(biāo)開始,到結(jié)尾 String s1 = buffer.substring(2); System.out.println(s1); //結(jié)果: cdefg //截取一段,從某個角標(biāo)到某個角標(biāo) (不包尾) String s2 = buffer.substring(2,5); System.out.println(s2);//結(jié)果:cde }
- public String substring(int start)
-
StringBuffer和String的相互轉(zhuǎn)換
- String -- >StringBuffer
- 通過構(gòu)造方法
- 通過StringBuffer的append方法
- StringBuffer --> String
- 通過toString()方法
- 通過subString(0,length)
- String -- >StringBuffer
-
-
案例
-
數(shù)組轉(zhuǎn)成字符串
- 需求: 使用StringBuffer將數(shù)組中的數(shù)據(jù)按照指定格式拼接成一個字符串
- 輸入結(jié)果: [ 1, 2, 3]
public static void main(String[] args) { int[] arr = {6,5,8,7}; StringBuffer buffer = new StringBuffer(); buffer.append("["); for (int i = 0; i < arr.length; i++) { if (i==arr.length-1) { buffer.append(arr[i]).append("]"); }else{ buffer.append(arr[i]).append(","); } } System.out.println(buffer.toString());//結(jié)果: [6,5,8,7] }
-
字符串反轉(zhuǎn)
- 需求: 從鍵盤錄入一個字符串,對字符串進(jìn)行反轉(zhuǎn)
public static void main(String[] args) { Scanner scanner =new Scanner(System.in); String str = scanner.nextLine(); StringBuffer buffer = new StringBuffer(str); buffer.reverse(); System.out.println(buffer.toString()); scanner.close(); }
-
二. StringBuilder
-
定義
StringBuilder功能等同于Stringbuffer, 線程不安全,效率高, 單線程下建議使用StringBuilder
-
StringBuffer和StringBuilder的區(qū)別
- StringBuffer是jdk1.0版本開始的,是線程安全的,效率低
- StringBuilder是jdk1.5版本開始的,是線程不安全的,效率高
三. 基本數(shù)據(jù)類型的包裝類
-
定義
? 基本數(shù)據(jù)類型自身沒有方法, 這樣就限制了我們的使用, 將基本數(shù)據(jù)類型封裝成對象的好處在于可以在對象中定義更多的功能方法操作該數(shù)據(jù)
-
對應(yīng)關(guān)系表
基本數(shù)據(jù)類型 引用數(shù)據(jù)類型 byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean -
常用方法
- 用于基本數(shù)據(jù)類型和字符串之間的轉(zhuǎn)換
public static void main(String[] args) { String str = "100"; int num = Integer.parseInt(str); System.out.println(num*5); //結(jié)果: 500 }
-
自動裝箱和拆箱
- 自動裝箱: 把基本數(shù)據(jù)類型轉(zhuǎn)換為包裝類型
- 自動拆箱: 把包裝類型轉(zhuǎn)換成基本數(shù)據(jù)類型
public static void main(String[] args) { Integer ii = 100;//自動裝箱 int i = ii; //自動拆箱 }
-
測試題
Integer i1 = new Integer(97); Integer i2 = new Integer(97); System.out.println(i1 == i2); System.out.println(i1.equals(i2)); System.out.println("-----------"); Integer i3 = new Integer(197); Integer i4 = new Integer(197); System.out.println(i3 == i4); System.out.println(i3.equals(i4)); System.out.println("-----------"); Integer i5 = 97; Integer i6 = 97; System.out.println(i5 == i6); System.out.println(i5.equals(i6)); System.out.println("-----------"); Integer i7 = 197; Integer i8 = 197; System.out.println(i7 == i8); System.out.println(i7.equals(i8));
四. Math
-
定義
? Math類包含用于執(zhí)行基本數(shù)學(xué)運(yùn)算的方法, 如初等指數(shù),對數(shù),平方根和三角函數(shù)
-
常用方法
- public static int abs(int a) : 返回一個數(shù)的絕對值
- public static double ceil(double a) : 返回大于等于參數(shù)的最小整數(shù)
- public static double floor(double a) : 返回小于等于參數(shù)的最大整數(shù)
- public static int max(int a,int b) : 獲取最大值
- public static double pow(double a,double b) : 計算某個數(shù)的幾次冪
- public static double random() : 獲取一個大于等于0且小于1的隨機(jī)數(shù)
- public static int round(float a) : 對象小數(shù)四舍五入
- public static double sqrt(double a) : 計算平方根
五. Random
-
定義
- 此類用于產(chǎn)生偽隨機(jī)數(shù)
- 之所以說是為隨機(jī)數(shù),是因為產(chǎn)生的數(shù)是使用一個算法算出的
- 如果用相同的種子創(chuàng)建兩個 Random 實例剩失,則對每個實例進(jìn)行相同的方法調(diào)用序列屈尼,它們將生成并返回相同的數(shù)字序列
-
構(gòu)造方法
- public Random()
- public Random(long seed)
-
常用的方法
- public int nextInt()
- public int nextInt(int n)(重點掌握) : 產(chǎn)生一個0到參數(shù)(不包括)之內(nèi)的隨機(jī)整數(shù)
public static void main(String[] args) { Random random = new Random(); int num = random.nextInt(100); System.out.println(num); }
-
測試題
隨機(jī)生成一個4位整數(shù)的驗證碼
六. System
-
常用的方法
- public static void gc() : 暗示垃圾回收器運(yùn)行
- public static void exit(int status) : 虛擬機(jī)退出
- public static long currentTimeMillis() : 獲取當(dāng)前時間的毫秒值
- pubiic static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) : 復(fù)制數(shù)組
-
演示
public static void main(String[] args) { new Demo(); //創(chuàng)建一個匿名對象,當(dāng)程序執(zhí)行完這句話之后,這個對象就沒用了 System.gc();//暗示調(diào)用垃圾回收器 ,能不能回收,看臉 long time = System.currentTimeMillis();//獲取當(dāng)前時間的毫秒值 System.out.println(time); System.out.println(".........."); System.exit(0); //退出jvm System.out.println(".........."); //將不會執(zhí)行 }
七. BigInteger
-
定義
? 我們平時使用的數(shù)值類型都有一定的長度限制,當(dāng)我們要運(yùn)算的數(shù)超過了長度限制之后就無法使用了, 這時我們就可以使用BigInteger,他可以裝載其他類型表示的任意長度的數(shù)值
-
構(gòu)造方法
- public BigInteger(String val)
-
成員方法
- public BigInteger add(BigInteger augend) : 加
- public BigInteger subtract(BigInteger subtrahend) : 減
- public BigInteger multiply(BigInteger multiplicand) : 乘
- public BigInteger divide(BigInteger divisor) : 除
- public BigInteger[] divideAndRemainder(BigInteger val) : 返回除積和余數(shù)
-
演示
public static void main(String[] args) { BigInteger bi = new BigInteger("10551020110102100"); BigInteger bi2 = new BigInteger("100"); System.out.println(bi.add(bi2));//10551020110102200 System.out.println(bi.subtract(bi2));//10551020110102000 System.out.println(bi.multiply(bi2));//1055102011010210000 System.out.println(bi.divide(bi2));//105510201101021 }
八. BigDecimal
-
定義
- 由于在運(yùn)算的時候,float類型和double很容易丟失精度拴孤,演示案例脾歧。
- 所以,為了能精確的表示演熟、計算浮點數(shù)鞭执,Java提供了BigDecimal
- 不可變的、任意精度的有符號十進(jìn)制數(shù)芒粹。
-
構(gòu)造方法
- public BigDecimal(String val)
-
常用方法
- public BigDecimal add(BigDecimal augend) : 加
- public BigDecimal subtract(BigDecimal subtrahend) : 減
- public BigDecimal multiply(BigDecimal multiplicand) : 乘
- public BigDecimal divide(BigDecimal divisor) : 除
-
演示
public static void main(String[] args) { BigDecimal b1 = new BigDecimal("2.0"); // 推薦使用傳入字符串的形式 BigDecimal b2 = new BigDecimal("1.1"); System.out.println(b1.add(b2));//結(jié)果:3.1 System.out.println(b1.subtract(b2));//結(jié)果:0.9 System.out.println(b1.multiply(b2));//結(jié)果:2.20 System.out.println(b1.divide(b2));//沒有確定的結(jié)果 }
九. Date
-
定義
? Date類表示特定的瞬間, 精確到毫秒
-
構(gòu)造方法
- public Date()
- public Date(long date)
-
常用方法
- public long getTime()
- public void setTime(long time)
-
演示
public static void main(String[] args) { Date date = new Date(); System.out.println(date.toString());//表示瞬時時間的字符串 結(jié)果: Mon Oct 30 22:50:48 CST 2017 System.out.println(date.getTime());//獲取瞬時時間的毫秒值 結(jié)果:1509375048974 date.setTime(1509379011190L);//設(shè)置時間點 System.out.println(date.toString());//表示瞬時時間的字符串 結(jié)果:Mon Oct 30 23:56:51 CST 2017 }
十. SimpleDateFormat(非常重要)
-
定義
? 時間格式化工具,她以與語言無關(guān)的方式格式化并解析日期或時間
-
構(gòu)造方法
- public SimpleDateFormat()
- public SimpleDateFormat(String pattern) 使用一個字符串時間格式
-
常用方法
- public final String format(Date date)
- public Date parse(String source)
-
時間格式標(biāo)識符
字母 日期或時間元素 表示 示例 G Era 標(biāo)志符 Text AD y 年 Year 1996;96 M 年中的月份 Month July;jul;07 w 年中的周數(shù) Number 27 W 月份中的周數(shù) Number 2 D 年中的天數(shù) Number 189 d 月份中的天數(shù) Number 10 F 月份中的星期 Number 8 E 星期中的天數(shù) Text Tuesday;Tue a Am/pm 標(biāo)記 Text PM H 一天中的小時數(shù)(0-23) Number 0 k 一天中的小時數(shù)(1-24) Number 24 K am/pm 中的小時數(shù)(0-11) Number 0 h am/pm 中的小時數(shù)(1-12) Number 12 m 小時中的分鐘數(shù) Number 30 s 分鐘中的秒數(shù) Number 55 S 毫秒數(shù) Number 978 z 時區(qū) General time zone Pacific Standard Time;PST;GMT-08:00 Z 時區(qū) RFC 822 time zone -0800 -
演示
public static void main(String[] args) throws ParseException { Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); String format = dateFormat.format(date); System.out.println(format); // 結(jié)果: 2017-10-30 23:08:58 Date date2 = dateFormat.parse("2017-05-1 10:13:22");//將字符串時間轉(zhuǎn)成Date時間 System.out.println(date2);//結(jié)果 : 2017-10-30 23:08:58 }
-
測試題
- 從鍵盤錄入一個時間 xx年xx月xx日xx時xx分xx秒, 將這個時間轉(zhuǎn)化成毫秒值保存下來
十一. Calendar(非常重要)
-
定義
- Calendar 類是一個抽象類兄纺,它為特定瞬間與一組諸如 YEAR、MONTH化漆、DAY_OF_MONTH估脆、HOUR 等日歷字段之間的轉(zhuǎn)換提供了一些方法,并為操作日歷字段(例如獲得下星期的日期)提供了一些方法
- Calendar 是一個萬年歷
-
成員方法
- public static Calendar getInstance() 獲取萬年歷對象
- public int get(int field) 獲取時間的某個值
- public void add(int field,int amount) 在當(dāng)前時間的基礎(chǔ)上加上一段時間
- public final void set(int year,int month,int date)設(shè)置時間點
-
Calendar的時間字段
- 具體查看API
- 常用的字段
- DAY_OF_MONTH 表示一個月中的某天
- DAY_OF_WEEK表示一個星期中的某天
- DAY_OF_YEAR表示當(dāng)前年中的天數(shù)
- HOUR_OF_DAY表示一天中的小時
- YEAR表示年份
- MONTH表示月份
- WEEK_OF_MONTH 表示當(dāng)前月中的星期數(shù)
-
演示
public static void main(String[] args) throws ParseException { Calendar calendar = Calendar.getInstance(); //獲取當(dāng)前時間的日歷對象 System.out.println(calendar.getTime());//表示當(dāng)前時間 結(jié)果:Mon Oct 30 23:26:47 CST 2017 System.out.println(calendar.getTimeInMillis());//獲取當(dāng)前時間的毫秒值 結(jié)果:1509377207751 calendar.add(Calendar.MONTH, 1);//給當(dāng)前時間加1個月 System.out.println(calendar.getTime());//結(jié)果: Thu Nov 30 23:28:16 CST 2017 calendar.add(Calendar.MONTH, -2);//給當(dāng)前時間減2個月 System.out.println(calendar.getTime());//結(jié)果: Sat Sep 30 23:28:48 CST 2017 calendar.set(Calendar.YEAR, 2015);//設(shè)置年份 System.out.println(calendar.getTime());//結(jié)果: Wed Sep 30 23:29:41 CST 2015 calendar.set(Calendar.MONTH, 3);//月份是從0開始的 System.out.println(calendar.getTime());//結(jié)果: Thu Apr 30 23:33:32 CST 2015 calendar.set(Calendar.DAY_OF_MONTH, 3);//設(shè)置日 System.out.println(calendar.getTime());//結(jié)果: Fri Apr 03 23:35:05 CST 2015 }
-
測試題
- 需求: 從鍵盤錄入一個年份,判斷當(dāng)年是閏年還是平年
- 解題思路: 閏年的2月是29天 平年的2月是28天
public static void main(String[] args) throws ParseException { Scanner scanner = new Scanner(System.in); System.out.println("請輸入年份"); int year = scanner.nextInt(); Calendar calendar = Calendar.getInstance(); calendar.set(year, 2, 1);//設(shè)置日期,某年的3月1日 calendar.add(Calendar.DAY_OF_MONTH, -1);//將時間減1天,就變成了2月的最后一天 int day = calendar.get(Calendar.DAY_OF_MONTH);//獲取到這一天在當(dāng)月中的數(shù)值 if (day==29) { System.out.println("今年是閏年"); }else{ System.out.println("今年是平年"); } scanner.close(); }
總結(jié)
- StringBuffer (重中之重)
- 是一個可變的字符序列
- 其實就是一個可以改變長度的存放字符串的容器
- 增 : append insert
- 刪 : deleteCharAt delete
- 改 : setCharAt replace
- 查 : charAt indexOf
- StringBuilder (和StringBuffer一樣 )
- 線程不安全, 效率高
- 基本數(shù)據(jù)類型的包裝類(重點)
- parseXXX()
- 其他類(不重要)
- Math
- System
- BigInteger
- BigDcimal
- Random(重點)
- nextInt()
- nextInt(b-a+1) +a (a-b 都包含)
- nextInt(b-a) +a (a-b b包含)
- Date (重點)
- 表示當(dāng)前時間
- getTime
- setTime
- SimpleDateFormat(重點)
- 時間格式化
- format 將Date轉(zhuǎn)成字符串
- parse 將字符串轉(zhuǎn)成Date
- Calendar (重中之重)
- get
- set
- add
作業(yè)
- 第一題
- 需求: 創(chuàng)建一個int型數(shù)組,從鍵盤錄入數(shù)據(jù),使用next()方法獲取數(shù)據(jù),存入數(shù)組中, 遍歷數(shù)組
- 注意: 對異常進(jìn)行處理,循環(huán)錄入, 直到輸入"結(jié)束",終止程序,遍歷數(shù)組
- 第二題
- 需求: 從鍵盤錄入一個字符串,判斷字符串是否對稱(使用StringBuffer和StringBuilder)
- 第三題(有漏洞,不準(zhǔn)時replace())
- 需求: 有一個字符串, 給字符串中所有字符 '我' 添加上引號
- 示例: 我與父親不想見已二年余了, 我最不能忘記的是他的背影
- 結(jié)果: "我"與父親不想見已二年余了, "我"最不能忘記的是他的背影
- 第四題
- 需求: 從鍵盤錄入兩個時間, 計算這個兩個時間之間相差的天數(shù)
- 注意: 不足一天算一天
- 擴(kuò)展題
- 需求: 編寫程序, 使用循環(huán), 比較StringBuffer,StringBuilder和 + 之間的效率問題
一. 對象數(shù)組的概述和使用
-
案例演示
- 需求: 創(chuàng)建5個學(xué)生對象, 將對象存入到數(shù)組中,遍歷數(shù)組,打印學(xué)生信息
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n8" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
Student[] sts = new Student[5];sts[0] = new Student("小紅", 18);
sts[1] = new Student("小明", 19);
sts[2] = new Student("小白", 20);
sts[3] = new Student("小輝", 21);
sts[4] = new Student("小張", 23);for (int i = 0; i < sts.length; i++) {
System.out.println(sts[i]);
}
}</pre> -
解析
數(shù)組中存放的是對象的地址值
遍歷數(shù)組時就可以拿到引用地址值,調(diào)用對象完成方法
二. 集合概述
-
概述
我們都知道,數(shù)組的長度是不可變的, 當(dāng)元素的個數(shù)超過數(shù)組的長度之后, 我們就只能通過創(chuàng)建長度更長的新數(shù)組的方式來存儲元素, 太麻煩了
集合給我提供另外一種容器的概念,可變長度的容器, 這樣,程序在使用的時候就不需要再考慮容器容量的問題,從而可以更加專心于業(yè)務(wù)
我們要知道,java中數(shù)組是唯一的底層容器,所有, 集合是開發(fā)者使用java規(guī)范制作的邏輯上的容器
-
數(shù)組和集合的區(qū)別
-
區(qū)別1
數(shù)組既可以存儲基本數(shù)據(jù)類型, 又可以儲存引用數(shù)據(jù)類型,基本數(shù)據(jù)類型存儲的是值, 引用數(shù)據(jù)類型儲存的是地址值
集合只能存儲引用數(shù)據(jù)類型(對象的引用), 其實集合也可以存儲基本數(shù)據(jù)類型, 但是在存儲的時候自動裝箱變成包裝類對象
-
區(qū)別2
數(shù)組長度是固定的,不能自動增長
集合的長度的是可變的,可以根據(jù)元素的增加而增長
-
-
使用場景
如果元素的個數(shù)是固定的,推薦使用數(shù)組
如果元素的個數(shù)不固定,推薦使用集合(日常開發(fā)中,使用集合比較普遍)
-
集合體系圖
[圖片上傳失敗...(image-55d5cb-1575623003230)]
-
集合分類
-
Collection集合
- 單列集合, 直接存儲對象的引用
-
Map集合
- 雙列集合, 使用key-value的形式, 每個元素會有一個唯一的名稱
-
三. Collection集合
-
定義
Collection是單列集合, 用于存儲單個元素
Collection是一個接口, 他的下面有多個子接口和實現(xiàn)類, 我們稱之為Collection體系
-
分類
List 集合中的元素是有序的,可以存放重復(fù)元素
Queue 隊列, 除優(yōu)先級外, 保持先進(jìn)先出的原則(基本不用)
Set 集合中的元素是無序的, 不能存放重復(fù)的元素
體系圖
-
常用方法
boolean add(E e) 添加元素
boolean remove(Object o) 從此 collection 中移除指定元素的單個實例获三,如果存在的話
void clear() 移除此 collection 中的所有元素
boolean contains(Object o) 判斷集合中是否包含指定元素
boolean isEmpty() 判斷集合中元素的個數(shù)是否為空
int size() 獲取集合中元素的個數(shù)
-
案例演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n105" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
//如果沒有泛型,會報出警告,不影響運(yùn)行
Collection<Student> collection = new ArrayList<>();Student student1 = new Student("小紅", 18);
Student student2 = new Student("小明", 19);collection.add(student1); //添加方法
collection.add(student2);//判斷集合中是否包含某個元素
System.out.println(collection.contains(student1));//結(jié)果為 : true//判斷集合中元素的個數(shù)是否為null
System.out.println(collection.isEmpty());//結(jié)果: false//獲取集合中元素的個數(shù)
System.out.println(collection.size());//結(jié)果為 : 2//移除某個元素
System.out.println(collection.remove(student2));//結(jié)果:true
System.out.println(collection.size());//結(jié)果: 1//清空集合中的元素
collection.clear();
System.out.println(collection.size());//結(jié)果為0
}</pre> -
集合中所有帶All的方法
boolean addAll(Collection c) 將指定 collection 中的所有元素都添加到此 collection 中
boolean removeAll(Collection c) 移除此 collection 中那些也包含在指定 collection 中的所有元素
boolean containsAll(Collection c) 如果此 collection 包含指定 collection 中的所有元素
boolean retainAll(Collection c) 僅保留此 collection 中那些也包含在指定 collection 的元素
演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n119" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();Student student1 = new Student("小紅", 18);
Student student2 = new Student("小明", 19);collection.add(student1); //添加方法
collection.add(student2);Collection<Student> collection2 = new ArrayList<>();
Student student3 = new Student("小輝", 18);
collection2.add(student1);
collection2.add(student3);//將collection2集合中的元素添加到collection集合中
collection.addAll(collection2);
System.out.println(collection.size());//結(jié)果: 4
?
//判斷collection集合中是否包含collection2集合中的所有元素
boolean flg = collection.containsAll(collection2);
System.out.println(flg);//結(jié)果: true//僅在collection中保留兩個集合中相同的元素
collection.retainAll(collection2);
System.out.println(collection.size());//結(jié)果: 3
}</pre>
四. 迭代器
-
定義
- 集合是用來存儲元素,存儲的元素需要查看,那么就需要迭代(遍歷)
-
案例演示遍歷集合
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n129" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();Student student1 = new Student("小紅", 18);
Student student2 = new Student("小明", 19);
Student student3 = new Student("小輝", 18);collection.add(student1); //添加方法
collection.add(student2);
collection.add(student3);//集合轉(zhuǎn)數(shù)組進(jìn)行遍歷
Object[] obs= collection.toArray();for (int i = 0; i < obs.length; i++) {
System.out.println(obs[i]); //前提集合內(nèi)的元素重寫了toString()方法
}
}</pre> -
迭代器的遍歷形式
-
步驟
獲取迭代器
調(diào)用hashNext()方法判斷下一個元素是否存在
調(diào)用next()方法獲取元素
演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n144" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();Student student1 = new Student("小紅", 18);
Student student2 = new Student("小明", 19);
Student student3 = new Student("小輝", 18);collection.add(student1); //添加方法
collection.add(student2);
collection.add(student3);//for循環(huán)的形式
for(Iterator<Student> it = collection.iterator();it.hasNext();){
Student student = it.next();
System.out.println(student);
}//while循環(huán)的形式
Iterator<Student> it = collection.iterator();
while(it.hasNext()){
Student student = it.next();
System.out.println(student);
}
}</pre> -
-
迭代器工作原理
Iterator是一個接口,規(guī)定了迭代器的基本使用, 集合的子類都實現(xiàn)了迭代器方法, 同時返回屬于自己的迭代器對象
迭代器相當(dāng)于是集合的一個副本, 里面記錄了集合的基本屬性值.
使用時,我們先調(diào)用hashNext方法判斷是否有下一個元素,如果有則返回true,否則返回false
然后調(diào)用next()方法,返回當(dāng)前指針?biāo)谖恢蒙系脑?/p>
-
修改集合導(dǎo)致的異常
當(dāng)我們使用迭代器遍歷集合的時候,如果對集合進(jìn)行了修改,下一次循環(huán)會報錯
原因: 集合會記錄修改的次數(shù), 如果迭代器發(fā)現(xiàn)集合副本和原集合修改次數(shù)不一樣的話就會報錯
解決辦法: 使用迭代器的刪除方法
演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n167" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();Student student1 = new Student("小紅", 18);
Student student2 = new Student("小明", 19);collection.add(student1); //添加方法
collection.add(student2);
?
//while循環(huán)的形式
Iterator<Student> it = collection.iterator();
while(it.hasNext()){
Student student = it.next();
//collection.remove(student);
it.remove();
}
}</pre>
五. List集合
-
定義
List集合是有序的,可以儲存重復(fù)的數(shù)據(jù)
List集合通過記錄元素在集合中的位置來準(zhǔn)確的查找元素
-
List集合體系
ArrayList 底層使用數(shù)組(線程不安全)
LinkedList 底層使用鏈表
Vector 底層使用數(shù)組(線程安全的,不推薦使用)
六. ArrayList集合
-
定義
低層使用的是數(shù)組, 所以其特性非常接近于數(shù)組
儲存的元素是有序的,而且可以重復(fù)存儲, 通過數(shù)組角標(biāo)來查詢更改元素,速度非撑园快
由于每次增刪都要改動數(shù)組中的角標(biāo),所有導(dǎo)致增刪效率低下
-
ArrayList的增刪改查原理
ArrayList 集合初始化會有一個默認(rèn)長度是10的數(shù)組, 內(nèi)部還有一個記錄當(dāng)前元素個數(shù)的變量, 當(dāng)儲存的元素個數(shù)超過數(shù)組長度之后,容量就會擴(kuò)充一半
當(dāng)我們?nèi)ゲ樵兗现械脑貢r, 需要提供給集合一個角標(biāo)值, 然后通過這個角標(biāo)值查找集合中的元素
當(dāng)我們?nèi)h除一個元素的時候, 集合就會根據(jù)角標(biāo)刪除這個元素,并且改動其他元素的位置,這就是導(dǎo)致增刪緩慢的原因
其實如果我們是連續(xù)往集合尾部插入數(shù)據(jù)的話, 速度其實是非常快的, 因為其他元素的位置不需要改動,但是如果我們插入數(shù)據(jù)的位置是數(shù)組的前面或者中間,速度就會有明顯的降低
-
構(gòu)造方法
ArrayList() 構(gòu)造一個初始化容量為10的空列表
ArrayList(Collection<? exends E> e) 構(gòu)造一個包含執(zhí)行集合元素的列表
ArrayList(int initialCapacity) 構(gòu)造一個具有指定初始容量的空列表
-
常用方法
boolean add(E e) 將指定的元素添加到此列表的尾部
void add(int index,E element) 將指定的元素插入此列表中的指定位置
boolean contains(Object o) 如果此列表中包含指定的元素,則返回true
E get(int index) 通過角標(biāo)查找元素
int indexOf(Object o) 返回此列表中首次出現(xiàn)的指定元素的索引, 或如果沒有則返回 -1
int lastIndexOf(Object o) 返回此列表中最后一次出現(xiàn)的指定元素的索引(從后先前查)沒有返回-1
boolean remove(Object o) 移除此列表中首次出現(xiàn)的指定元素(如果存在)
E set(int index , E element) 用指定元素替代此列表中指定位置上的元素,返回原來的元素
int size() 返回此列表中的元素數(shù)
-
演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n240" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();//添加元素
list.add("小紅");
list.add("小明");
//將元素添加到角標(biāo)1上
list.add(1,"小輝");System.out.println(list.contains("小明"));//true
//通過角標(biāo)獲取
String str = list.get(1);
System.out.println(str);//結(jié)果: 小輝//通過元素獲取角標(biāo)
System.out.println(list.indexOf("小明"));//結(jié)果 : 2//通過角標(biāo)移除元素
System.out.println(list.remove(1));//結(jié)果: true//通過角標(biāo)設(shè)置元素
System.out.println(list.set(1, "小李"));//小輝}</pre>
-
ArrayList集合的遍歷
for 循環(huán)遍歷, 基本上等同于數(shù)組
演示
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="java" cid="n248" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();list.add("小紅");
list.add("小明");
list.add("小輝");for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}</pre>迭代器 使用公用迭代器
演示
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="java" cid="n254" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();list.add("小紅"); list.add("小明"); list.add("小輝"); Iterator<String> it = list.iterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); }
}
</pre>迭代器2 List集合的迭代器(ListIterator) 可以從后往前遍歷
演示
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="java" cid="n260" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();list.add("小紅"); list.add("小明"); list.add("小輝"); ListIterator<String> it = list.listIterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); } while(it.hasPrevious()){ String str = it.previous(); System.out.println(str); }
}
</pre> -
測試題
去除集合中的重復(fù)字符串元素
演示
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="java" cid="n268" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("a");
list.add("b");
list.add("b");
list.add("b");
list.add("c");
list.add("c");
list.add("c");
list.add("c");
list.add("a");System.out.println(list); ArrayList newList = getSingle(list); System.out.println(newList);
}
</pre>
七. LinkedList集合
-
定義
底層使用的是鏈表,就好像一條鎖鏈
這個集合中的每個元素都被封裝到一個叫Node的內(nèi)部類中, 然后記錄上一個元素和下一個元素的地址,通過手拉手形成一個鏈條
增刪快, 查詢慢
-
增刪改查的原理
當(dāng)需要去查詢LinkedList集合中的元素時,需要從最開始的元素查找起,然后一層一層往后找,直到找到該元素,這樣的動作十分消耗性能
當(dāng)需要去刪除元素的時候, 我們只需要將被刪除元素兩端的元素重新連接到一起,或者新增的時候?qū)⑿略睾妥笥覂蛇叺脑剡B起來就可以了
-
構(gòu)造方法
LinkedList() 構(gòu)造一個空列表
LinkedList(Collection<? extends E> e) 構(gòu)造一個包含指定collection中元素的列表
-
常用方法
E remove() 獲取并移除此列表的頭
E poll() 獲取并移除此列表的頭
E peek() 獲取但不移除此列表的頭
-
演示
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="java" cid="n305" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;">public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();list.add("小紅"); list.add("小明"); list.add("小輝"); System.out.println(list.remove());//結(jié)果: 小紅 System.out.println(list.size());//結(jié)果:2 System.out.println(list.poll());//結(jié)果: 小明 System.out.println(list.size());//結(jié)果:1 System.out.println(list.peek());//結(jié)果: 小輝 System.out.println(list.size());//結(jié)果:1
}
</pre>
八. ArrayList, LinkedList 及Vector集合之間的區(qū)別
-
線程安全
Vector : 線程安全
ArrayList, LinkedList : 線程不安全
-
實現(xiàn)方式
LinkedList : 鏈表
ArrayList,Vector : 數(shù)組
-
擴(kuò)容
ArrayList和Vector使用數(shù)組實現(xiàn), 當(dāng)數(shù)組長度不夠,內(nèi)部會創(chuàng)建一個更大的數(shù)組
LinkedList 不存在這方面的問題
-
速度
ArrayList 查改塊, 增刪慢
LinkedList 查改慢, 增刪快
總結(jié)
-
StringBuffer和StringBuilder
高級的字符串, 可以變長度的字符序列
StringBuffer安全效率低, StringBuilder不安全,效率高
-
包裝類
八個基本數(shù)據(jù)類型的包裝類
自動裝箱和自動拆箱
每個包裝類中都有一個可以將字符串轉(zhuǎn)成基本數(shù)據(jù)類型的方法 xxx.parseXXX();
-
Random
生成隨機(jī)數(shù)
nextInt()
nextInt(int num)
生成一個a - b(包含a,不包含b的隨機(jī)數(shù)) nextInt(b-a)+a;
生成一個a - b(包含a,包含b的隨機(jī)數(shù)) nextInt(b-a+1)+a;
-
集合
ArrayList 底層數(shù)組 增刪慢 查改塊
LinkedList底層鏈表 增刪塊 查改慢
這里的增指的是 插入 , 實際上如果是尾部添加, ArrayList反而更塊
作業(yè)
-
第一個題
- 需求: 定義一個swap()方法,傳入集合和兩個角標(biāo),將兩個角標(biāo)上的元素交換位置
-
第二題
- 需求: 創(chuàng)建一個Student類,定義name和age屬性,創(chuàng)建幾個Student對象放入集合中,遍歷集合,查找年齡最大的對象,并打印
-
第三題
- 需求: 定義集合讓集合中添加多個元素,然后將集合中的元素位置反轉(zhuǎn)
-
第四題
- 需求: 創(chuàng)建一個Student類,定義name和age屬性, 創(chuàng)建幾個對象存入集合中(有重復(fù)屬性的對象),創(chuàng)建方法去除集合中的重復(fù)元素
-
擴(kuò)展題
-
第一題
- 需求: 現(xiàn)在有16只球隊, 科特迪瓦疙教,阿根廷棺聊,澳大利亞,塞爾維亞贞谓,荷蘭限佩,尼日利亞、日本,美國祟同,中國作喘,新西 蘭,巴西晕城,比利時泞坦,韓國,喀麥隆砖顷,洪都拉斯贰锁,意大利. 將這16只球隊存入到集合中,然后隨機(jī)分成4組存入到4個集合中.遍歷打印集合
-
第二題
需求: 創(chuàng)建一個Student類, 定義 姓名,年齡,班級,成績 屬性, 然后創(chuàng)建多個對象存入集合中, 求出所有學(xué)生的平均年齡和每個班級的平均成績
Student類的屬性如下所示
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="java" cid="n415" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background: rgb(51, 51, 51); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 10px 10px 30px; width: inherit;"> private String name;
private int age;
private int score;
private String ClassNum;
</pre>
-