集合
集合類的特點:提供一種存盤空間可變的存盤模型,存盤的資料容量可以隨時發生改變,
1. Collection(介面):單列集合
List(介面):元素可重復
ArrayList(實作類):
LinkedList(實作類):
Set(介面):元素不可重復
HashSet(實作類):
TreeSet(實作類):
2. Map(介面):雙列集合
HashMap(實作類):
Collection集合
1. Collection是單列集合的頂層介面,
2. Collection沒有任何具體的實作類,創建物件時必須使用子類介面List或Set的實作類,
創建Collection集合物件的方式
- 多型的方式
- 具體的實作類,如ArrayList
public class CollectionDemo {
public static void main(String[] args) {
//創建Collection物件
Collection<String> cc = new ArrayList<>();
//添加元素 String型別
cc.add("茶碗兒");
cc.add("雀巢咖啡");
//運行結果:[茶碗兒, 雀巢咖啡]
//說明重寫了toString()方法
System.out.println(cc);
}
}
Collection集合的常用方法
- boolean add() 添加元素
- boolean remove() 移除指定元素
- void clear() 清空集合
- boolean contains() 判斷集合是否包含指定元素
- isEmpty() 判斷集合是否為空
- int size() 獲取集合的長度
Collection集合的遍歷
- iterator:迭代器,集合的專用遍歷方式,iterator() 回傳集合中的迭代器,
- 迭代器中的方法
- E next() 回傳迭代中的下一個元素,也就是獲取元素的,
- boolean hasNext() 如果迭代中具有更多元素,回傳true,也就是用來判斷元素是否存在,
//Collection集合的遍歷
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> cc = new ArrayList<>();
cc.add("茶碗兒");
cc.add("雀巢咖啡");
cc.add("五香鹵蛋");
Iterator<String> it = cc.iterator();
//先判斷元素是否存在,再獲取元素
while (it.hasNext()){
String s = it.next();
System.out.println(s);
}
}
}
運行結果:
茶碗兒
雀巢咖啡
五香鹵蛋
練習:創建Collection集合,添加三個學生物件,遍歷
//學生類
public class Student {
private String Name;
private int age;
public Student() {
}
public Student(String name, int age) {
Name = name;
this.age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重寫toString()
@Override
public String toString() {
return "Student{" +
"Name='" + Name + '\'' +
", age=" + age +
'}';
}
}
//測驗類
public class StudentDemo {
public static void main(String[] args) {
//創建Collection集合,型別為學生類
Collection<Student> co = new ArrayList<>();
//創建學生物件
Student s1 = new Student("茶碗兒", 11);
Student s2 = new Student("花生糖", 12);
Student s3 = new Student("燕麥片", 13);
//向集合中添加元素
co.add(s1);
co.add(s2);
co.add(s3);
//獲取集合中的迭代器
Iterator<Student> it = co.iterator();
//遍歷集合
while (it.hasNext()){
System.out.println(it.next());
}
}
}
//運行結果
Student{Name='茶碗兒', age=11}
Student{Name='花生糖', age=12}
Student{Name='燕麥片', age=13}
List集合
特點
- List集合:有序集合,有索引,元素可重復
- 可精確控制元素的插入位置,可通過索引訪問指定元素
總結
- 有序:存盤和取出的元素順序一致
- 可重復:存盤的元素可重復
List集合特有方法
- void add(int index,E element) 在集合中指定位置,插入指定的元素,
- E remove(int index) 洗掉指定索引處的元素,回傳被洗掉的元素,
- E set(int index,E element) 修改指定索引處的元素,回傳被修改的元素,
- E get(int index) 回傳指定索引處的元素,
//遍歷List集合
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("java");
list.add("world");
for (String s : list) {
System.out.println(s);
}
}
}
//運行結果
hello
java
world
并發修改例外 ConcurrentModificationException
案例:
//判斷集合里是否有元素"world",如果有,則像集合中添加元素"javaee"
public class ListDemo2 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("java");
list.add("world");
Iterator<String> it = list.iterator();
while(it.hasNext()){
String s = it.next();
if (s.equals("world")){
//通過集合物件,向集合中添加元素
list.add("javaee");
}
}
System.out.println(list);
}
}
運行結果
//并發修改例外 ConcurrentModificationException
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at com.chawaner.test4.ListDemo2.main(ListDemo2.java:25)
并發修改例外產生的原因:
迭代器通過next()方法獲取元素時會判斷預期修改值和實際修改值是否相等,迭代器遍歷元素程序中,如果集合物件通過add()方法修改了集合中的元素,就會導致預期修改值和實際修改值不一致,
解決方案
如果需要在遍歷操作中插入元素,使用for回圈遍歷(普通for回圈,不是迭代器for),然后用集合物件操作即可,
解決方案:
public class ListDemo2 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("java");
list.add("world");
//增強for,其實就是迭代器遍歷,會出現并發修改例外
//for (String s : list) {
// if (s.equals("world")){
// list.add("javaee");
// }
//}
//使用for回圈解決并發修改例外
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (s.equals("world")){
list.add("javaee");
}
}
System.out.println(list);
}
}
運行結果:
[hello, java, world, javaee]
串列迭代器
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add("java");
//獲取串列迭代器 listIterator()
ListIterator<String> it = list.listIterator();
//遍歷
System.out.println("遍歷集合:");
//判斷下一個元素是否存在 hasNext()
while (it.hasNext()){
//獲取下一個元素 next()
System.out.println(it.next());
}
//逆向遍歷
System.out.println("逆向遍歷集合:");
//判斷前一個元素是否存在 hasPrevious()
while (it.hasPrevious()){
//獲取前一個元素 previous()
System.out.println(it.previous());
}
//遍歷時向集合中插入元素
while (it.hasNext()){
String s = it.next();
if (s.equals("world")){
/*通過串列迭代器,將指定的的元素插入集合;
迭代器中沒有add()方法,而串列迭代器中有add()方法;
串列迭代器中的add()方法會把實際修改值賦值給預期修改值;
next()方法獲取元素時判斷預期修改值和實際修改值是否相等,就不會出現并發修改例外,
*/
it.add("吃飯");
}
System.out.println(list);
}
}
增強for回圈
增強for簡化了陣列和集合的遍歷
- JDK5之后出現,內部原理是包裝了一個Iterator迭代器
案例:
public static void main(String[] args) {
int[] arr = {15, 45, 56, 98, 32};
//陣列遍歷
for (int i : arr) {
System.out.println(i);
}
System.out.println("---------------");
List<String> list = new ArrayList<>();
list.add("黑化肥發黑會揮發");
list.add("喝咖啡就大蒜");
list.add("雞你太美接化發");
//集合遍歷
for (String s : list) {
System.out.println(s);
}
}
運行結果:
15
45
56
98
32
---------------
黑化肥發黑會揮發
喝咖啡就大蒜
雞你太美接化發
List集合存盤物件的三種遍歷方式
- 普通for回圈遍歷:帶有索引的遍歷方式
- 迭代器遍歷:集合特有的遍歷方式
- 增強for遍歷:最方便的遍歷方式
常見的資料結構
- 堆疊:先進后出(水桶)
- 佇列:先進先出(管道)
- 陣列:查詢快,增刪慢
- 查詢元素通過索引定位,查詢任意元素耗時相同,查詢速度快
- 洗掉資料時,要將原始將元素洗掉,同時后面每個元素要前移,洗掉效率低
- 添加資料時,先所有元素后移一位,才能在指定位置添加元素,添加效率極低
- 鏈表:增刪快,查詢慢(都是相比陣列而言)
- 鏈表元素被稱為結點
- 結點有地址(存盤位置),地址里面有資料和下一個結點的地址
- ^:結點指向空地址,表示結束
- 添加:添加到指定位置,更改前一個結點的指向,更改要添加的結點的指向到后面的節點
- 洗掉:更改前一個結點的指向,再洗掉指定結點
- 查詢:從頭開始查詢,查詢速度慢
- 哈希表:
- JDK8之前,底層采用陣列+鏈表,即元素為鏈表的陣列結構
- JDK8之后,在長度比較長的時候,底層實作了優化(略)
List集合子類特點:使用的時候,要考慮場景是查詢還是增刪
- List集合常用子類:ArrayList,LinkedList
- ArrayList:底層資料結構是陣列(查詢快,增刪慢)
- LinkedList:底層資料結構是鏈表(查詢慢,增刪快)
基本使用案例:
public static void main(String[] args) {
//ArrayList添加元素
List<String> arr = new ArrayList<>();
arr.add("雞你太美");
arr.add("接化發");
arr.add("耗子尾汁");
ListIterator<String> ait = arr.listIterator();
//串列迭代器遍歷查詢,并添加元素
while (ait.hasNext()) {
String s = ait.next();
if (s.equals("接化發")) {
ait.add("偷襲");
}
}
//增強for遍歷ArrayList集合
for (String s : arr) {
System.out.println(s);
}
System.out.println("-----------------");
//LinkedList添加物件
List<Student> lin = new LinkedList<>();
Student s1 = new Student("曹操", 11);
Student s2 = new Student("劉備", 12);
Student s3 = new Student("孫權", 13);
lin.add(s1);
lin.add(s2);
lin.add(s3);
//增強for遍歷集合
for (Student student : lin) {
System.out.println(student);
}
}
運行結果:
雞你太美
接化發
偷襲
耗子尾汁
-----------------
Student{Name='曹操', age=11}
Student{Name='劉備', age=12}
Student{Name='孫權', age=13}
LinkedList特有的方法
public static void main(String[] args) {
//創建一個LinkedList
LinkedList<String> list = new LinkedList<>();
//添加元素
list.add("雞你太美");
list.add("接化發");
list.add("混元形意太極門");
list.add("耗子尾汁");
//輸出集合
System.out.println("串列:"+list);
//在串列開頭插入指定元素 public void addFirst()
list.addFirst("所有人下來做核酸");
//在串列末尾添加元素 public void addLast()
list.addLast("叮咚雞");
System.out.println("首尾插入元素后的串列:"+list);
//回傳串列中的第一個元素 public E getFirst()
System.out.println("回傳串列第一個元素:"+list.getFirst());
//回傳串列中的最后一個元素 public E getLast()
System.out.println("回傳串列最后一個元素:"+list.getLast());
//移除并回傳串列第一個元素 public E removeFirst()
System.out.println("移除并回傳串列第一個元素:"+list.removeFirst());
//移除并回傳串列最后一個元素 public E removeLast()
System.out.println("移除并回傳串列最后一個元素:"+list.removeLast());
System.out.println("移除首尾元素后的串列:"+list);
}
運行結果:
串列:[雞你太美, 接化發, 混元形意太極門, 耗子尾汁]
首尾插入元素后的串列:[所有人下來做核酸, 雞你太美, 接化發, 混元形意太極門, 耗子尾汁, 叮咚雞]
回傳串列第一個元素:所有人下來做核酸
回傳串列最后一個元素:叮咚雞
移除并回傳串列第一個元素:所有人下來做核酸
移除并回傳串列最后一個元素:叮咚雞
移除首尾元素后的串列:[雞你太美, 接化發, 混元形意太極門, 耗子尾汁]
Set集合
- 不允許元素重復
- 沒有帶索引的方法,不能使用普通for回圈遍歷
HashSet:對集合的迭代順序不做任何保證,就是說遍歷是亂序的,
public static void main(String[] args) {
//Set集合存盤字串并遍歷
Set<String> set = new HashSet<>();
set.add("混元形意太極門");
set.add("馬保國");
set.add("馬保國");
set.add("接化發");
//HashSet遍歷不保證順序
for (String s : set) {
System.out.println(s);
}
}
運行結果:Set集合不包含重復的元素
接化發
馬保國
混元形意太極門
哈希值
- 哈希值:是JDK根據物件的地址或者字串或者數字算出來的int型別的數值,
- Object類中有一個hashCode()方法可以獲取物件的哈希值,
public class HashCodeDemo {
public static void main(String[] args) {
Student s = new Student("馬保國", 69);
//Object類中有一個hashCode()方法可以獲取物件的哈希值
//回傳一個int型別的哈希碼值
System.out.println("馬保國哈希值:"+s.hashCode());
System.out.println("馬保國哈希值:"+s.hashCode());
Student s1 = new Student("挖掘機", 25);
System.out.println("挖掘機哈希值:"+s1.hashCode());
}
}
運行結果:
馬保國哈希值:189568618
馬保國哈希值:189568618
挖掘機哈希值:666641942
- 默認使用Object類下的hashCode()方法下,同一個物件的哈希值相同,不同物件的哈希值不同,
- 重寫hashCode()方法,可以使不同物件哈希值相同,
- 字串String重寫了hashCode()方法,兩個不同字串物件的哈希碼值有可能相同,
//這倆字串物件的哈希值都是:1179395
System.out.println("重地".hashCode());
System.out.println("通話".hashCode());
HashSet集合
HashSet集合的特點
- 底層資料結構是哈希表
- 對集合迭代順序不保證,不保證存盤和取出的元素順序一致
- 沒有帶索引的方法,不能使用普通for回圈遍歷
- 不包含重復的元素
HashSet集合添加一個元素的程序
- 呼叫物件的hashCode()獲取物件的哈希值
- 根據哈希值計算物件的存盤位置
- 判斷該位置是否有元素存在
- 如果沒有,將元素存放到該位置
- 如果有,遍歷該位置元素比較哈希值
??如果哈希值不相同,存盤元素到該位置
??如果哈希值相同,呼叫equals()比較物件內容
????如果內容也相同,不保存該元素
????如果內容不相同,存盤元素到該位置
總結:
HashSet集合添加一個元素的程序,首先要比較哈希值是否相同,哈希值不相同則保存元素;哈希值相同時,還要比較元素的內容是否相同,元素的內容不相同時才保存元素,
HashSet集合保證元素唯一性
- 要保證元素唯一性,需要重寫hashCode()和equals()
哈希表
- 元素為鏈表的陣列,默認長度為16(0-15),
- 存盤元素的時候,用元素的哈希值對16取余(%16),余數是幾,就將元素存盤在幾的位置(每個位置都是一個鏈表),
- 元素存進某個位置里的鏈表中,要對比這個位置里的鏈表中的元素的哈希值和內容(即:遵循HashSet集合的元素唯一性),
案例
public class HashCodeDemo1 {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<>();
Student s1 = new Student("曹操", 11);
Student s2 = new Student("劉備", 12);
Student s3 = new Student("孫權", 13);
Student s4 = new Student("孫權", 13);
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
for (Student h : hs) {
System.out.println(h);
}
}
}
運行結果
Student{Name='孫權', age=13}
Student{Name='劉備', age=12}
Student{Name='曹操', age=11}
Student{Name='孫權', age=13}
這塊添加重復元素成功了,說明不是同一個物件,如果不保存重復元素,需要重寫Student類里面的hashCode()和equals(),如下:
public class Student {
private String Name;
private int age;
public Student() {
}
public Student(String name, int age) {
Name = name;
this.age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重寫toString方法
@Override
public String toString() {
return "Student{" +
"Name='" + Name + '\'' +
", age=" + age +
'}';
}
//重寫equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return Name != null ? Name.equals(student.Name) : student.Name == null;
}
//重寫hashCode方法
@Override
public int hashCode() {
int result = Name != null ? Name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
再看運行結果:這下就沒有重復元素了
Student{Name='孫權', age=13}
Student{Name='劉備', age=12}
Student{Name='曹操', age=11}
LinkedHashSet集合
特點:有序,元素不重復
- 哈希表和鏈表實作的Set介面,具有可預測的迭代次序
- 由鏈表保證元素有序,也就是說元素的存盤和取出順序是一致的
- 由哈希表保證元素唯一,也就是說沒有重復元素
案例:LinkedHashSet集合存盤字串并遍歷
public class HashCodeDemo1 {
public static void main(String[] args) {
LinkedHashSet<String> lhs = new LinkedHashSet<>();
lhs.add("春天");
lhs.add("夏天");
lhs.add("夏天");
lhs.add("秋天");
lhs.add("冬天");
for (String lh : lhs) {
System.out.println(lh);
}
}
}
運行結果:有序,元素不重復
春天
夏天
秋天
冬天
TreeSet集合
特點
- 元素有序,指的不是存取的順序,而是按照某種規則進行排序,排序方式取決于構造方法,
- TreeSet():根據元素的自然排序進行排序
- TreeSet(Comparator comparator):根據指定的比較器進行排序
- 沒有帶索引的方法,不能使用普通for回圈遍歷,
- 由于是Set集合,所以元素不重復,
案例:TreeSet集合存盤整數并遍歷
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<>();
ts.add(10);
ts.add(30);
ts.add(20);
ts.add(20);
ts.add(50);
ts.add(40);
for (Integer t : ts) {
System.out.println(t);
}
}
}
運行結果:自然排序(從小到大),元素不重復
10
20
30
40
50
自然排序Comparable
案例:
public class ComparableDemo {
public static void main(String[] args) {
/*存盤學生物件并遍歷,創建TreeSet集合使用無參構造方法
* 要求:按照年齡從小到大排序,年齡相同時,按照姓名的字母順序排序*/
TreeSet<Student> ts = new TreeSet<>();
Student s1 = new Student();
s1.setName("Tom");
s1.setAge(11);
Student s2 = new Student();
s2.setName("Carl");
s2.setAge(12);
Student s3 = new Student();
s3.setName("Bob");
s3.setAge(13);
Student s4 = new Student();
s4.setName("iKun");
s4.setAge(12);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
for (Student t : ts) {
System.out.println(t);
}
}
}
運行結果:型別轉換例外,要實作自然排序,Student類要實作Comparable介面并重寫compareTo()
Exception in thread "main" java.lang.ClassCastException: class com.chawaner.test5.Student cannot be cast to class java.lang.Comparable (com.chawaner.test5.Student is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.TreeMap.compare(TreeMap.java:1291)
at java.base/java.util.TreeMap.put(TreeMap.java:536)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at com.chawaner.test5.ComparableDemo.main(ComparableDemo.java:29)
修改Student類:
public class Student implements Comparable<Student>{
private String Name;
private int age;
public Student() {
}
public Student(String name, int age) {
Name = name;
this.age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重寫toString
@Override
public String toString() {
return "Student{" +
"Name='" + Name + '\'' +
", age=" + age +
'}';
}
//重寫equals
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return Name != null ? Name.equals(student.Name) : student.Name == null;
}
//重寫hashCode
@Override
public int hashCode() {
int result = Name != null ? Name.hashCode() : 0;
result = 31 * result + age;
return result;
}
//重寫compareTo
@Override
public int compareTo(Student o) {
//回傳0,表示添加的第二個元素跟第一個元素是同一個元素,所以只會添加第一個元素成功
return 0;
}
}
運行結果:只會添加第一個元素成功
Student{Name='Tom', age=11}
如果將compareTo方法里面的回傳值改為1,則會認為第二個元素比第一個元素大,第二個元素就會添加到第二個元素后面,遍歷時,就是按照元素的添加順序輸出結果
//重寫compareTo
@Override
public int compareTo(Student o) {
//回傳0,表示添加的第二個元素跟第一個元素是同一個元素,所以只會添加第一個元素成功.
//回傳1,則會認為第二個元素比第一個元素大,第二個元素就會添加到第二個元素后面,遍歷時,就是按照元素的添加順序輸出結果,同理,回傳-1則會按照倒序添加元素成功,
return 1;
}
運行結果:添加元素成功
Student{Name='Tom', age=11}
Student{Name='Carl', age=12}
Student{Name='Bob', age=13}
Student{Name='iKun', age=12}
修改compareTo(),按照年齡排序
//重寫compareTo,按照年齡排序
@Override
public int compareTo(Student o) {
//從小到大排序
//當前要存盤的元素 this.age,上一個元素 o.age
int num = this.age - o.age;
//從大到小排序
//int num = o.age - this.age;
return num;
}
運行結果:年齡從小到大排序,但是年齡相同的元素值保存成功了第一個
Student{Name='Tom', age=11}
Student{Name='Carl', age=12}
Student{Name='Bob', age=13}
修改compareTo(),按照年齡從小到大排序,年齡相同時,按照姓名首字母排序
@Override
public int compareTo(Student o) {
//按照年齡規則,從小到大排序
//當前要存盤的元素 this.age,上一個元素 o.age
int num = this.age - o.age;
//從大到小排序
//int num = o.age - this.age;
//年齡相同時,按照姓名首字母順序排序
//Name是個字串,String實作了Comparable<String>,所以能直接呼叫compareTo(T o)實作自然排序
//三目運算,當年齡相同,按照姓名自然排序,否則按照年齡規則排序
int num2 = num == 0 ? this.Name.compareTo(o.Name) : num;
return num2;
}
運行結果:年齡從小到大排序,年齡相同時,按照姓名首字母順序排序
Student{Name='Tom', age=11}
Student{Name='Carl', age=12}
Student{Name='iKun', age=12}
Student{Name='Bob', age=13}
再測一下姓名和年齡都相同時,能否保證元素的唯一性
public class ComparableDemo {
public static void main(String[] args) {
/*存盤學生物件并遍歷,創建TreeSet集合使用無參構造方法
* 要求:按照年齡從小到大排序,年齡相同時,按照姓名的字母順序排序*/
TreeSet<Student> ts = new TreeSet<>();
Student s1 = new Student();
s1.setName("Tom");
s1.setAge(11);
Student s2 = new Student();
s2.setName("Carl");
s2.setAge(12);
Student s3 = new Student();
s3.setName("Bob");
s3.setAge(13);
Student s4 = new Student();
s4.setName("iKun");
s4.setAge(12);
Student s5 = new Student();
s5.setName("Bob");
s5.setAge(13);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
for (Student t : ts) {
System.out.println(t);
}
}
}
運行結果:姓名和年齡都相同時,保證了元素的唯一性
Student{Name='Tom', age=11}
Student{Name='Carl', age=12}
Student{Name='iKun', age=12}
Student{Name='Bob', age=13}
TreeSet集合總結
- 能夠按照規則排序,并且能對元素去重
- 重寫compareTo方法時,要注意排序規則,按照要求的主要條件(num)和次要條件(num2)來寫
比較器排序Comparator
要求:存盤學生物件并遍歷,創建TreeSet集合,使用帶參構造方法創建學生物件
- 使用比較器Comparator按照年齡從小到大排序,年齡相同時,按照姓名的字母順序排序
public class ComparatorDemo {
public static void main(String[] args) {
//TreeSet里面有一個Comparator介面,實際用的是Comparator的實作類物件
//這里使用匿名內部類的方法,使用比較器Comparator來實作排序
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//按照年齡規則排序
//現在是在測驗類里面,所以不能直接訪問Student類的成員變數age,得用getAge()
int num = s1.getAge() - s2.getAge();
//按照年齡規則排序,年齡相同時,按照姓名自然排序
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
return num2;
}
});
//使用帶參構造方法創建元素
Student s1 = new Student("Tom",11);
Student s2 = new Student("Carl",12);
Student s3 = new Student("Bob",13);
Student s4 = new Student("iKun",12);
Student s5 = new Student("Bob",13);
//添加元素到TreeSet集合
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
//增強for遍歷集合
for (Student t : ts) {
System.out.println(t);
}
}
}
運行結果:
Student{Name='Tom', age=11}
Student{Name='Carl', age=12}
Student{Name='iKun', age=12}
Student{Name='Bob', age=13}
結論:
- 自然排序:是在學生類里面,重寫compareTo(T o),自定義排序規則
- 比較器排序,是在測驗類里面,讓集合接收一個Comparator介面的實作類物件,重寫compare(T o1,T o2)方法
- 重寫方法時,一定要按照 要求的主要條件(num)和次要條件(num2)來寫
泛型
- 泛型<常見的:T,E,K,V>
- 本質是引數化型別
- 將型別由原來具體的引數化,在使用/呼叫時傳入具體的型別
- 泛型的好處
- 把運行時期遇到的問題提前到了編譯時期
- 避免了強制型別轉換
泛型類
案例:
//定義一個泛型類,生成set/get方法
public class Generic<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
//測驗類
public class GenericDemo {
public static void main(String[] args) {
//根據泛型創建物件
Generic<String> g1 = new Generic<>();
//根據泛型設定資訊
g1.setT("小明");
System.out.println(g1.getT());
Generic<Integer> g2 = new Generic<>();
g2.setT(12);
System.out.println(g2.getT());
}
}
運行結果:泛型類可以定義任何型別
小明
12
泛型方法
案例:
//泛型類
public class Generic {
/**
* 回傳型別為傳入引數的型別
* @param t
* @param <T>
*/
public <T> void show(T t) {
System.out.println(t);
}
}
//測驗類
public class GenericDemo {
public static void main(String[] args) {
//根據傳入的引數型別,回傳相同型別的回傳值
Generic g = new Generic();
g.show("小明");
g.show(12);
g.show(true);
}
}
運行結果:
小明
12
true
泛型介面
//定義一個泛型介面
public interface Generic<T> {
void show(T t);
}
//定義一個泛型介面的實作類
public class GenericImpl<T> implements Generic<T>{
@Override
public void show(T t) {
System.out.println(t);
}
}
//測驗類
public class GenericDemo {
public static void main(String[] args) {
Generic<String> g1 = new GenericImpl<>();
g1.show("小明");
Generic<Integer> g2 = new GenericImpl<>();
g2.show(32);
}
}
運行結果:
小明
32
型別通配符
型別通配符:<?> 表示任意型別
型別通配符的上限:<? extends 型別> 表示的型別是當前型別或者其子類
型別通配符的下限:<? super 型別> 表示的型別是當前型別或者其父類
public class GenericDemo {
public static void main(String[] args) {
//型別通配符<?> 表示任意型別
List<?> l1 = new ArrayList<Object>();
List<?> l2 = new ArrayList<Number>();
List<?> l3 = new ArrayList<Integer>();
// 型別通配符的上限 <? extends 型別>
// 表示的型別是Number或者其子類
List<? extends Number> l4 = new ArrayList<Number>();
List<? extends Number> l5 = new ArrayList<Integer>();
// 型別通配符的下限 <? super Number>
// 表示的型別是Number或者其父類
List<? super Number> l6 = new ArrayList<Object>();
}
}
可變引數
修飾符 回傳值型別方法名(資料型別...變數名){}
如:public static int sum(int...a){}
public class GenericDemo1 {
public static void main(String[] args) {
//呼叫可變引數方法求和
System.out.println(sum(10));
System.out.println(sum(10, 20));
System.out.println(sum(10, 20, 30));
}
/**
* 可變引數求和
* @param a 其實是個陣列
* @return 求和結果
* 如果除了可變引數以外還有別的引數,要將可變引數放在后面
* 如:public static int sum(int b,int...a){}
*/
public static int sum(int...a){
//定義sum并初始化
int sum = 0;
//遍歷陣列元素,求和
for (int i : a) {
sum += i;
}
return sum;
}
}
運行結果:
10
30
60
- Arrays工具類中有一個靜態方法:
- public static
List asList(T... a):回傳由指定陣列支持的固定大小的串列 - 回傳的集合不能做增刪操作,可以做修改操作
- List介面中有一個靜態方法:
- public static
List of(E... elements):回傳包含任意數量元素的不可變串列 - 回傳的集合不能做增刪改操作
- Set介面中有一個靜態方法:
- public static
Set of(E... elements) :回傳一個包含任意數量元素的不可變集合 - 在給元素的時候,不能給重復的元素
- 回傳的集合不能做增刪操作,沒有修改的方法
Map集合
- public interface Map<K,V>
- K:鍵的型別,V:值的型別
- 將鍵映射到值的物件,不能包含重復的鍵;每個鍵只能映射到一個值,
public class MapDemo {
public static void main(String[] args) {
//多型的方式創建Map集合
//具體的實作類HashMap
Map<String, String> m = new HashMap<>();
m.put("001","小紅");
m.put("002","小明");
m.put("002","小軍");
m.put("004","小剛");
System.out.println(m);
}
}
運行結果:鍵不能重復,鍵相同的情況下,后面的元素會覆寫前面的元素,
//HashMap集合重寫了toString()
{001=小紅, 002=小軍, 004=小剛}
Map集合的常用方法

public class MapDemo {
public static void main(String[] args) {
Map<String, String> m = new HashMap<>();
//添加元素
m.put("001","小明");
m.put("002","小紅");
m.put("003","小剛");
System.out.println(m);
//集合的長度
System.out.println("集合的長度:"+m.size());
//判斷集合是否為空
System.out.println("集合是否為空:"+m.isEmpty());
//根據鍵洗掉元素
m.remove("001");
System.out.println("根據鍵001洗掉元素后的集合:"+m);
//判斷是否包含指定的鍵
System.out.println("否包含鍵002:"+m.containsKey("002"));
//判斷是否包含指定的值
System.out.println("是否包含小剛:"+m.containsValue("小剛"));
//洗掉所有元素
m.clear();
System.out.println("洗掉所有元素后的集合長度:"+m.size());
//判斷集合是否為空
System.out.println("集合是否為空:"+m.isEmpty());
}
}
運行結果:
{001=小明, 002=小紅, 003=小剛}
集合的長度:3
集合是否為空:false
根據鍵001洗掉元素后的集合:{002=小紅, 003=小剛}
否包含鍵002:true
是否包含小剛:true
洗掉所有元素后的集合長度:0
集合是否為空:true
Map集合的獲取功能

public class MapDemo {
public static void main(String[] args) {
//創建集合物件
Map<String, String> m = new HashMap<>();
//添加元素
m.put("001", "小明");
m.put("002", "小紅");
m.put("003", "小剛");
//輸出集合
System.out.println("集合:" + m);
//根據鍵獲取值
System.out.println("根據鍵001獲取值:" + m.get("001"));
//獲取所有鍵
System.out.println("獲取所有鍵:" + m.keySet());
//獲取所有值
System.out.println("獲取所有值:" + m.values());
//獲取所有鍵值對物件,HashMap重寫了toString()
System.out.println("獲取所有鍵值對物件:" + m.entrySet());
}
}
運行結果:
集合:{001=小明, 002=小紅, 003=小剛}
根據鍵001獲取值:小明
獲取所有鍵:[001, 002, 003]
獲取所有值:[小明, 小紅, 小剛]
//HashMap重寫了toString()
獲取所有鍵值對物件:[001=小明, 002=小紅, 003=小剛]
Map集合的遍歷
兩種遍歷方法
- 鍵找值:獲取所有的鍵,遍歷鍵,根據鍵獲取對應的值
- 鍵值對物件找鍵和值:獲取所有鍵值對物件,遍歷鍵值對物件,根據鍵值對物件獲取對應的鍵和對應的值
public class MapDemo {
public static void main(String[] args) {
/*獲取所有的鍵,遍歷鍵,根據鍵獲取對應的值*/
//創建集合
Map<String, String> m = new HashMap<>();
//添加元素
m.put("001", "小明");
m.put("002", "小紅");
m.put("003", "小剛");
//獲取所有鍵
Set<String> keySet = m.keySet();
//遍歷鍵
for (String s : keySet) {
//根據鍵獲取對應的值
System.out.println(m.get(s));
}
}
}
運行結果:
小明
小紅
小剛
public class MapDemo {
public static void main(String[] args) {
/*獲取所有鍵值對物件,遍歷鍵值對物件,根據鍵值對物件獲取對應的鍵和對應的值*/
//創建集合
Map<String, String> m = new HashMap<>();
//添加元素
m.put("001", "小明");
m.put("002", "小紅");
m.put("003", "小剛");
//獲取所有鍵值對物件,鍵值對物件型別 Map.Entry<String, String>
Set<Map.Entry<String, String>> entries = m.entrySet();
//遍歷鍵值對物件
for (Map.Entry<String, String> entry : entries) {
//根據鍵值對物件獲取對應的鍵和對應的值
System.out.println(entry.getKey()+"---"+entry.getValue());
}
}
}
運行結果:
001---小明
002---小紅
003---小剛
統計字串中每個字串出現的次數
public class MapDemo {
public static void main(String[] args) {
/*統計字串中字符出現的次數*/
//初始化字串
String s = "aabbbcceddeccaabeed";
//創建集合 鍵:字符 值:次數
Map<Character, Integer> m = new HashMap<>();
//遍歷字串,拿到每一個字符
for (int i = 0; i < s.length(); i++) {
//用拿到每一個字符作為鍵,到HashMap集合中去找對應的值,看回傳值
char key = s.charAt(i);
//該字符出現的次數
Integer value = https://www.cnblogs.com/chawaner/p/m.get(key);
//如果回傳值為null,說明該字符在HashMap集合中不存在,是第一次出現,設定值為1
if (value == null){
//存盤元素到HashMap集合中 HashMap<字符,出現次數>
m.put(key,1);
}else {//如果回傳值不為null,說明該字符在HashMap集合中存在,讓值+1
//該字符出現的次數+1
value++;
//重新存盤,覆寫原有值(HashMap集合鍵的唯一性)
m.put(key,value);
}
}
//創建StringBuilder可變字串
StringBuilder sb = new StringBuilder();
//遍歷HashMap集合,得到鍵的值
//遍歷所有鍵,通過建找到對應值
for (Character key : m.keySet()) {
Integer value = m.get(key);
//像字串中添加元素
sb.append(key+"("+value+")");
}
//輸出結果
System.out.println("統計字串中字符出現的次數:" + sb.toString());
}
}
運行結果
統計字串中字符出現的次數:a(4)b(4)c(4)d(3)e(4)
Collections工具類
Collections類是操作集合的工具類
Collections類中常用的方法
- public static void sort(List
list):將指定的串列按升序排序將指定的串列按升序排序 - public static void reverse(List<?> list):反轉指定串列中元素的順序
- public static void shuffle(List<?> list):使用默認的隨機源隨機排列指定的串列
public class CollectionsDemo {
public static void main(String[] args) {
//創建集合
ArrayList<Integer> arr = new ArrayList<>();
//添加元素
arr.add(20);
arr.add(10);
arr.add(30);
//輸出集合
System.out.println("集合:"+arr);
//升序排序
Collections.sort(arr);
System.out.println("升序排序:"+arr);
//反轉順序
Collections.reverse(arr);
System.out.println("反轉順序:"+arr);
//隨機排列
Collections.shuffle(arr);
System.out.println("隨機排列:"+arr);
}
}
運行結果:
集合:[20, 10, 30]
升序排序:[10, 20, 30]
反轉順序:[30, 20, 10]
隨機排列:[10, 30, 20]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537664.html
標籤:Java
