1 Set集合
1.1 Set集合概述
Set集合的元素是無序的,即存入的順序和取出的順序不一定是一致的。
Set集合中的元素不可以重複。
Set類是Collection的子類,所以Set集合的功能和Collection是一致的。
Set集合的取出方式只有一種:Iterator迭代器。
Set:元素是無序的(存入和取出的順序不一定一致),元素不可以重複,保證了元素唯一性。
|--HashSet:哈希表結構,線程不同步。
|--TreeSet:二叉樹結構,可以對Set集合中的元素進行排序。
1.2 HashSet集合
HashSet集合是Set集合的一種,所以具有Set集合的特點:元素無序且唯一。
HashSet是線程不同步的,無序、高效。
HashSet集合的數據結構是哈希表。
哈希表:
1,對集合元素對象中的關鍵字(特有數據),進行哈希算法的運算,得出一個具體的值,這個值成爲哈希值。
2,哈希值就是這個元素的位置。
3,如果哈希值出現衝突,再去判斷這個關鍵字對應的對象是否相同。如果對象相同,就不存儲,因爲元素重複。如果對象不同,就存儲,在原來對象的哈希值基礎 +1順延。
4,存儲哈希值的結構,我們稱爲哈希表。
5,既然哈希表是根據哈希值存儲的,爲了提高效率,最好保證對象的關鍵字是唯一的。
這樣可以儘量少的判斷關鍵字對應的對象是否相同,提高了哈希表的操作效率。
HashSet集合如何保證元素的唯一性?
是通過集合元素的兩個方法:hashcode()和equals()來完成。
如果元素的HashCode值(哈希值)相同,纔會判斷equals是否爲true。
如果元素的HashCode值不同,就不會再調用equals()方法。
碰到哈希表數據結構,就要想到hashcode()和equals(),比如HashSet、HashMap等。
注意:在HashSet集合中,對於判斷元素是否已存在,以及刪除等操作,依賴的方法是元素對象的hashcode()和equals()方法。
想刪除元素,或判斷元素,必須先判斷hashcode(),再判斷equals(),這就是HashSet集合的特點。
而在ArrayList集合中,判斷元素是否已存在,只根據equals()方法。
HashSet集合代碼示例:
import java.util.*;
class HashSetDemo2{
public static void main(String[] args){
HashSet hs = new HashSet();
hs.add(new Person("a1",11));
hs.add(new Person("a2",12));
hs.add(new Person("a3",13));
hs.add(new Person("a2",12)); //(a2,12)這個對象哈希地址值相同,再equals(),已有一個相同的對象
//這個(a2,12)就沒有存入集合。
//sop("a1--:"+hs.contains(new Person("a1",11)));
Iterator it = hs.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
sop(p.getName()+"..."+p.getAge());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class Person{
private String name;
private int age;
Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
/* hashCode()方法定義哈希值,哈希地址值相同,再判斷是否是同一個對象,此時才用的equals(),
如果哈希地址值不同,就用不到equals()。
String定義了hashCode(); age*23 是爲了防止不同對象姓名哈希值和age的和恰巧相同, */
public int hashCode(){
return name.hashCode()+age*23;
}
//自定義判斷對象是否重複的規則
public boolean equals(Object obj){
if(!(obj instanceof Person))
return false;
Person p =(Person)obj;
System.out.println(this.name+"...equals..."+p.name);
return this.name.equals(p.name) && this.age==p.age;
}
}
1.3 TreeSet集合
TreeSet集合的數據結構是二叉樹。
TreeSet集合是Set集合的一種,同樣有元素無序且唯一的特點。
TreeSet集合可以用來對Set集合中的元素進行排序。
TreeSet集合的代碼示例:
import java.util.*;
class TreeSetDemo{
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add("cba");
ts.add("abcd");
ts.add("aaa");
ts.add("bca"); //默認按照逐個字母的ASCII碼值進行排序。
Iterator it = ts.iterator();
while(it.hasNext()){
sop(it.next());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
1.4 TreeSet集合第一種排序方式:元素自身必備比較性
TreeSet集合的第一種排序方式:讓元素自身具備比較性。
元素需要實現Comparable接口,然後覆蓋comparaTo()方法。這樣元素自身就具備了比較性。
返回-1,則當前元素小於比較元素;返回1,則當前元素大於比較元素;返回0,則相同。
不做修改的默認順序,也叫做自然順序。
TreeSet第一種排序方式的代碼示例:
import java.util.*;
class TreeSetDemo2{
public static void main(String[] args){
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi007",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi01",19));
Iterator it = ts.iterator(); //迭代器遍歷
while(it.hasNext()){
Student stu = (Student)it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class Student implements Comparable { //該接口強制讓學生具備比較性。
private String name;
private int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
//覆蓋接口Comparable中的compareTo方法,讓學生具備比較性
public int compareTo(Object obj){
if(!(obj instanceof Student))
throw new RuntimeException("不是學生對象");
Student s = (Student)obj;
System.out.println(this.name+"...compareTo..."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)
//年齡相同時按姓名排序。String類實現了Comparable接口。
return this.name.compareTo(s.name);
return -1;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
1.5 TreeSet集合第二種排序方式:集合具備比較性
當元素自身不具備比較性,或者具備的比較性不是所需要的。
這時就需要讓容器TreeSet自身具備比較性。
定義一個比較器Comparator,將比較器對象作爲參數傳遞給TreeSet集合的構造函數。
自定義的Comparator的子類,需要覆蓋compare()方法,據此進行比較,然後將這個子類對象傳遞給TreeSet的構造函數,TreeSet集合就具備了比較性。
兩種排序方式,Comparator比較器的方式比較好。
需求:將上一節代碼TreeSetDemo2,從按照年齡排序改成按照姓名排序。
定義一個類,實現Comparator比較器接口,覆蓋compare()方法。
注意區別:Comparable接口中是compareTo()方法;而Comparator接口中是compare()方法。
同樣是根據return的值來判斷順序。
請看代碼示例:
import java.util.*;
class TreeSetDemo3{
public static void main(String[] args){
TreeSet ts = new TreeSet(new MyComparator()); //將比較器對象傳遞給TreeSet構造函數。
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi007",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi01",19));
Iterator it = ts.iterator();
while(it.hasNext()){
Student stu = (Student)it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class Student implements Comparable { //該接口強制讓學生具備比較性:按年齡排序
private String name;
private int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){ //覆蓋接口Comparable中的方法,進行比較
if(!(obj instanceof Student))
throw new RuntimeException("不是學生對象");
Student s = (Student)obj;
System.out.println(this.name+"...compareTo..."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name); //年齡相同是按姓名排序。
//String類實現了Comparable接口。
return -1;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
class MyComparator implements Comparator{ //比較器方法:實現Comparator接口,傳遞給TreeSet構造函數
public int compare(Object o1,Object o2){ //從而使TreeSet集合具有比較性,按照姓名排序
Student s1 = (Student)o1;
Student s2 = (Student)o2;
return s1.getName().compareTo(s2.getName());
}
}
1.6 TreeSet小練習
需求:根據字符串的長度進行排序。
使用第二中排序方式:比較器Comparator。
字符串String類的比較方法compareTo()比較的是自然順序,不是我們想要的。
所以使用Comparator比較器方式。
比較時可以使用Integer基本數據類型包裝類,比較int類型的自然順序。
代碼和註釋:
import java.util.*;
class TreeSetTest{
public static void main(String[] args){
TreeSet ts = new TreeSet(new StrComparator()); //比較器傳遞給TreeSet構造函數。
ts.add("abcd");
ts.add("cc");
ts.add("cba");
ts.add("aaa");
ts.add("hahaha");
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class StrComparator implements Comparator{
public int compare(Object o1,Object o2){
String s1 = (String)o1;
String s2 = (String)o2;
/* if(s1.length() < s2.length())
return -1;
if(s1.length()==s2.length())
return 0;
return 1; */
//基本數據類型包裝類Integer的compareTo()方法,比較自然順序。
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0) //如果字符串長度相同,再比較自然順序。
return s1.compareTo(s2); //調用String類的compareTo方法,根據自然順序比較。(ASCII碼)
return num;
}
}
2 Map集合
2.1 Map集合概述
Map集合和Collection集合不同,Collection集合存儲的是一個元素,一個一個的存。
Map集合存儲的是鍵值對(鍵:key,值:value),一對一對的往裏存,鍵和值有映射關係。
而且,要保證Map集合中“鍵”的唯一性。
Map(注意HashTable和HashMap的相同和不同)
HashTable:底層是哈希表數據結構,不可以存入null鍵和null值,該集合是線程同步的,(鍵和值不能爲空,效率較低)。
HashMap:底層是哈希表數據結構,可以存入null鍵和null值,該集合是線程不同步的,(鍵和值可以爲空,效率較高)。
TreeMap:底層是二叉樹數據結構,線程不同步,該集合可以用於給Map集合的鍵進行排序。
2.2 Map集合共性方法:
1,添加。
put(K key, V value):添加一個鍵值對,返回原來與“鍵”對應的“值”,沒有則返回null。
putAll(Map<? extends K, ? extends V> m):從指定映射中將所有映射關係複製到此映射中。
2,刪除。
clear():清空所有鍵值對。
removed(Object key):如果存在指定鍵的鍵值對,移除此鍵值對,並返回Value值。若不存在指定鍵的鍵值對,返回null。
3,判斷。
containsValue(Object value):是否包含有值爲value的鍵值對,有的話返回true。
containsKey(Object key):是否包含有鍵爲key的鍵值對,有的話返回true。
isEmpty():判斷集合是不是空的。
4,獲取。
get(Object key):根據“鍵”返回“值”。
size():返回“鍵值對”的個數。
values():返回一個Collection集合,此集合中存儲的是當前Map集合中所有“值”。
Map集合共性方法的簡單代碼示例:
import java.util.*;
class MapDemo{
public static void main(String[] args){
Map<String,String> map = new HashMap<String,String>(); //集合的多態
/* 添加元素
put方法的返回值是,返回原來與“鍵”對應的“值”,沒有則返回null。
這三個put方法都是返回null。 */
map.put("01","zhangsan");
map.put("02","lisi");
map.put("03","wangwu");
System.out.println("containsKey: "+map.containsKey("022")); //判斷
//System.out.println("remove: "+map.remove("02")); //刪除元素
System.out.println("get: "+map.get("02")); //獲取,get()根據“鍵”返回“值”。
//可以通過get()方法的返回值來判斷一個鍵是否存在,通過返回null來判斷。
//獲取Map集合中所有的值。
Collection<String> coll = map.values();
System.out.println("coll: "+coll);
System.out.println("map: "+map);
}
}
2.3 Map集合的兩種取出方式
Set<K> keySet();
Set<Map.Entry<K,Y>> entrySet();
Map集合的取出原理:將Map集合轉換成Set集合,再通過迭代器取出。
1,keySet:將Map集合中所有的“鍵”存入到Set集合,因爲Set有迭代器。
所以能使用迭代方式去除所有的“鍵”,再根據get方法,獲取對應的“值”。
2,entrySet:將Map集合中的映射關係取出,這個映射關係就是Map.Entry類型,即“鍵值對”。
那麼Map.Entry獲取到後,就可以通過Map.Entry中的getKey和getValue方法,獲取映射關係中的“鍵”和“值”。
接口Map.Entry介紹:
其實Entry也是一個藉口,它是Map接口中的一個內部接口。
interface Map{
public static interface Entry{ //子接口
public abstract Object getKey();
public abstract Object getValue();
}
}
Map集合兩種取出方式的代碼示例:
import java.util.*;
class MapDemo2{
public static void main(String[] args){
method_keySet();
method_entrySet();
}
public static void method_keySet(){
Map<String,String> map = new HashMap<String,String>();
map.put("02","zhangsan");
map.put("03","lisi");
map.put("01","wangwu");
//先獲取Map集合的所有“鍵”的Set集合,keySet();
Set<String> ks = map.keySet();
//有了Set集合,就可以獲取其迭代器。
Iterator<String> it = ks.iterator();
while(it.hasNext()){
String key = it.next();
String value = map.get(key); //有了“鍵”,可以通過Map集合的get方法取得對應的“值”
System.out.println("ketSet_Key: "+key+" ketSet_value: "+value);
}
}
public static void method_entrySet(){
Map<String,String> map = new HashMap<String,String>();
map.put("02","zhangsan");
map.put("03","lisi");
map.put("01","wangwu");
/* 將Map集合中的映射關係取出,存入到Set集合中。
此entrySet()方法返回值類型是Map.Entry<String,String>。 */
Set<Map.Entry<String,String>> en = map.entrySet();
Iterator<Map.Entry<String,String>> it = en.iterator();
//迭代器的next()方法返回類型與Iterator的元素類型一樣。
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
System.out.println("entrySet_Key: "+key+" entrySet_value: "+value);
}
}
}
2.4 HashMap集合
底層是哈希表數據結構,可以存入null鍵和null值,該集合是線程不同步的,(鍵和值可以爲空,效率較高)。
HashMap集合小練習:
需求:
每一個學生對象都有都有對應的歸屬地(學生Student,地址String)。
學生屬性:姓名,年齡。注意:姓名和年齡相同的,視爲同一個學生。
保證學生的唯一性。
思路:
1,Student類描述學生。
2,定義一個Map容器,將學生作爲“鍵”,地址作爲“值”,存入。
3,獲取Map集合中的鍵值對,再依次獲取鍵和值。
代碼:
import java.util.*;
class HashMapTest{
public static void main(String[] args){
HashMap<Student,String> map = new HashMap<Student,String>();
map.put(new Student("zhangsan",21),"Beijing");
map.put(new Student("lisi",22),"Shanghai");
map.put(new Student("wangwu",23),"Wuhan");
map.put(new Student("wangwu",23),"Changsha");
//獲取存儲鍵值對的Set集合。
Set<Map.Entry<Student,String>> s = map.entrySet();//迭代器
Iterator<Map.Entry<Student,String>> it = s.iterator();
while(it.hasNext()){
Map.Entry<Student,String> me = it.next();
Student key = me.getKey();
String value = me.getValue();
System.out.println("學生姓名:"+key.getName()+" 學生年齡:"+key.getAge()+" 地址:"+value);
}
}
}
class Student implements Comparable<Student> { //實現Comparable接口,使Student具有比較性。
public String name;
public int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public int hashCode(){ //hashCode()和equals()保證唯一性。保證“鍵”的唯一性。
return name.hashCode()+age*23;
}
public boolean equals(Object obj) {
if(!(obj instanceof Student))
throw new ClassCastException("類型不匹配"); //ClassCastException 是 RuntimeException的子類,可以不處理。
Student s = (Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
public int compareTo(Student s){ //重寫Comparable接口的compareTo()方法,定義比較性。
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
}
2.5 TreeMap集合
底層是二叉樹數據結構,線程不同步,該集合可以用於給Map集合的鍵進行排序。
TreeMap集合小練習:
需求:按照學生對象的姓名進行排序。
因爲數據是以“鍵-值”對的形式存在,所以要使用可以排序的Map集合:TreeMap。
TreeMap集合的構造方法可以傳遞Comparator比較器,而HashMap不可以。
集合構造方法傳遞Comparator比較器,可以使集合自身具備比較性。
代碼:
import java.util.*;
class TreeMapTest{
public static void main(String[] args){
TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());
tm.put(new Student("zhangsan",22),"Beijing");
tm.put(new Student("lisi",21),"Shanghai");
tm.put(new Student("wangwu",23),"Wuhan");
tm.put(new Student("wangwu",23),"Changsha");
Set<Map.Entry<Student,String>> en = tm.entrySet();
Iterator<Map.Entry<Student,String>> it = en.iterator(); //迭代器
while(it.hasNext()){
Map.Entry<Student,String> me = it.next();
Student key = me.getKey();
String value = me.getValue();
System.out.println("學生姓名:"+key.getName()+" 學生年齡:"+key.getAge()+" 地址:"+value);
}
}
}
class Student {
public String name;
public int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public int hashCode(){ //hashCode()和equals()保證唯一性。保證“鍵”的唯一性。
return name.hashCode()+age*23;
}
public boolean equals(Object obj) {
if(!(obj instanceof Student))
throw new ClassCastException("類型不匹配"); //ClassCastException 是 RuntimeException的子類,可以不處理。
Student s = (Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
/* public int compareTo(Student s){ //重寫Comparable接口的compareTo()方法,使集合的元素具備比較性。
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
} */
}
class StuNameComparator implements Comparator<Student> { //實現Comparator比較器,使集合自身具備比較性。
public int compare(Student s1,Student s2){
int num = s1.getName().compareTo(s2.getName());
if(num == 0)
return new Integer(s1.getAge()).compareTo(new Integer(s1.getAge()));
return num;
}
}
2.6 TreeMap集合練習
需求:
“sdfssdsdqwqewdfzzxcxc”獲取該字符串中的字母出現的次數。
希望打印結果:a(1)c(2)......
通過結果發現,每一個字母都有對應的次數。
說明字母和次數之間都有映射關係。
注意:當發現有映射關係時,可以選擇Map集合,因爲Map集合中存放的就是映射。當數據之間存在着映射關係時,就要先想到Map集合。
思路:
1,將字符串轉換成字符數組,因爲要對每一個字母進行操作。
2,定義一個Map集合,因爲打印結果的字母有順序,所以使用TreeMap集合。
3,遍歷字符數組:
將每一個字母作爲“鍵”去查Map集合。
如果返回null,就將該字母和數字1存入Map集合(字母是鍵,數字1是值)。
如果返回不是null,則說明該字母在Map集合已經存在並有對應次數。
那麼就獲取該次數並進行自增,然後將該字母和自增後的次數,存入Map集合。
4,將Map集合中的數據變成指定的字符串形式返回。
代碼示例:
import java.util.*;
class TreeMapTest2 {
public static void main(String[] args){
charCount("sdfssdsdqwqewdfzzxcxc");
}
public static void charCount(String str){
char[] chs = str.toCharArray();
//泛型中的是引用類型,所以要用基本數據類型包裝類。
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
for(int x=0;x<chs.length;x++){
Integer value = tm.get(chs[x]); //Map集合的get方法,根據“鍵”返回“值”
if(value==null)
tm.put(chs[x],1);
else{
value = value+1;
tm.put(chs[x],value);
}
}
System.out.println(tm);
StringBuilder sb = new StringBuilder(); //利用緩衝區StringBuider,打結果。
Set<Map.Entry<Character,Integer>> en = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = en.iterator();
while(it.hasNext()){
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer in = me.getValue();
sb.append(ch+"("+in+")");
}
System.out.println(sb);
}
}
3. Map集合擴展知識:集合嵌套集合
集合嵌套集合,即集合的元素中包含集合。
Map集合被使用,是因爲具備映射關係。
"yureban" "01" "zhangsan"
"yureban" "02" "lisi"
"jiuyeban" "01" "wangwu"
"jiuyeban" "02" "zhaoliu"
代碼示例:
import java.util.*;
class MapDemo3{
public static void main(String[] args){
HashMap<String,String> yure = new HashMap<String,String>();
yure.put("01","zhangsan");
yure.put("02","lisi");
HashMap<String,String> jiuye = new HashMap<String,String>();
jiuye.put("01","wangwu");
jiuye.put("02","zhaoliu");
HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();
czbk.put("yureban",yure);
czbk.put("jiuyeban",jiuye);
//getStudentInfo(jiuye);
//getStudentInfo(yure);
//遍歷czbk集合,獲取所有的教室
Iterator<String> it = czbk.keySet().iterator();
while(it.hasNext()){
String key = it.next();
HashMap<String,String> value = czbk.get(key);
getStudentInfo(value);
}
}
public static void getStudentInfo(HashMap<String,String> roomMap){
Iterator<String> it = roomMap.keySet().iterator();
while(it.hasNext()){
String id = it.next();
String name = roomMap.get(id);
System.out.println(id+":"+name);
}
}
}