目錄
前言
在編程時,可以使用數組來保存多個對象,但數組長度不可變化,一旦在初始化數組時指定了數組長度,這個數組長度就是不可變的。如果需要保存數量變化的數據,數組就有點無能爲力了。而且數組無法保存具有映射關係的數據,如成績表爲語文——79,數學——80,這種數據看上去像兩個數組,但這兩個數組的元素之間有一定的關聯關係。
爲了保存數量不確定的數據,以及保存具有映射關係的數據(也被稱爲關聯數組),Java 提供了集合類。集合類主要負責保存、盛裝其他數據,因此集合類也被稱爲容器類。Java 所有的集合類都位於 java.util 包下,提供了一個表示和操作對象集合的統一構架,包含大量集合接口,以及這些接口的實現類和操作它們的算法。
集合類和數組不一樣,數組元素既可以是基本類型的值,也可以是對象(實際上保存的是對象的引用變量),而集合裏只能保存對象(實際上只是保存對象的引用變量,但通常習慣上認爲集合裏保存的是對象)。
Java 集合類型分爲 Collection 和 Map,它們是 Java 集合的根接口,這兩個接口又包含了一些子接口或實現類。接下來,將細講Collection和Map。
一、Collection
概述:
collection接口是集合框架的頂級接口(set與list的父接口,不是map集合的父接口)
- List , Set繼承至Collection接口
- Set下主要有HashSet,LinkedHashSet,TreeSet
- List下主要有ArrayList,Vector,LinkedList
- Collection接口下還有個Queue接口,有PriorityQueue類、ArrayDueue類
- Queue、List、Set是同一級別的,都是繼承了Collection接口。
- LinkedList同時實現了Queue和List接口,其實Queue接口窄化了對LinkedList的方法的訪問權限(即在方法中的參數類型如果是Queue時,就完全只能訪問Queue接口所定義的方法 了,而不能直接訪問 LinkedList的非Queue的方法),以使得只有恰當的方法纔可以使用。
List 有序,可重複
ArrayList
特點: 底層數據結構是數組,查詢快,增刪慢。
線程不安全,效率高。
Vector
特點: 底層數據結構是數組,查詢快,增刪慢。
線程安全,效率低。
LinkedList
特點: 底層數據結構是鏈表,查詢慢,增刪快。
線程不安全,效率高。
Set 唯一(不重複)
HashSet
底層數據結構是哈希表。(唯一,無序)
如何來保證元素唯一性?
1.依賴兩個方法:hashCode()和equals()
LinkedHashSet
底層數據結構是鏈表和哈希表。(唯一,有序)
1.由鏈表保證元素有序(FIFO先入先出隊列)
2.由哈希表保證元素唯一
TreeSet
底層數據結構是紅黑樹。(唯一,有序)
1. 如何保證元素排序的呢?
自然排序
比較器排序
2.如何保證元素唯一性的呢?
根據比較的返回值是否是0來決定
補充說明:
- TreeSet的主要功能用於排序
- TreeSet做範圍查詢效率較高,在數據庫的索引中,範圍查詢較多,所以樹結構主要用來做索引,來提高查詢效率。
- HashSet只是通用的存儲數據的集合
- HashSet是最常用的,做等值查詢效率最高,在開發中,最常用到的就是等值查詢。
- LinkedHashSet的主要功能用於保證FIFO即有序的集合(先進先出)
- LinkedHashSet在一個集合既不能元素重複,又要記錄元素的添加順序時使用。一般使用較少。
- HashSet和LinkHashSet允許存在null數據,但是TreeSet中插入null數據時會報NullPointerException
- 三者都不是線程安全的,如果要使用線程安全可以 Collections.synchronizedSet()
- 三者數據插入速度對比:HashSet(無序) > LinkHashSet(FIFO隊列) > TreeSet(內部排序)
注意:這裏關於Set,我們先來了解四個問題
1、HashSet爲什麼是無序的
2、LinkedHashSet和TreeSet是有序的,具體是怎麼實現的
3、TreeSet的兩種排序方式怎麼實現
4、三者的插入性能比較
1、HashSet爲什麼是無序的
有序、無序是指在進行插入操作時,插入位置的順序性
那我們舉個例子,爲什麼HashSet是無序的
Set<String> set = new HashSet<String>();
set.add("hello");
set.add("hello");//重複元素
set.add("java");
set.add("world");
System.out.println(set);//[java, world, hello]
1)先看下HashSet的add源碼,會發現,該方法是將數據值存入到HashMap的key中,到這裏我們就明白了,HsahMap在保存數據時,順序是通過計算key的hash值和當前數組長度的 & 運算,計算保存數據的下標位置,所以說set是無序的。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2)我們可以點進去驗證一下put方法實現原理
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2、LinkedHashSet和TreeSet是有序的,具體是怎麼實現的
這裏我們對LinkedHashSet、TreeSet以及HashSet的排序做個測試,代碼如下:
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
TreeSet<String> treeSet = new TreeSet<>();
for (String data : Arrays.asList("hello","hello", "world", "java")) {
hashSet.add(data);
linkedHashSet.add(data);
treeSet.add(data);
}
//不保證有序
//輸出:HashSet :[world, java, hello]
System.out.println("HashSet :" + hashSet);
//FIFO先入先出隊列
//輸出:LinkedHashSet :[hello, world, java]
System.out.println("LinkedHashSet :" + linkedHashSet);
//內部實現排序
//默認進行正序排列,因爲這裏是字符串,所以是按首字母排序的
//輸出:TreeSet :[hello, java, world]
System.out.println("TreeSet :" + treeSet);
}
結論:
- HashSet:無序(key的hash值和當前數組長度的 & 運算),不重複
- LinkedHashSet:有序(FIFO先入先出隊列),不重複
- TreeSet:有序(自然排序和比較器排序),不重複
3、TreeSet的兩種排序方式怎麼實現
在講TreeSet兩種排序前我們先做兩個測試:
3.1基本數據類型的排序
public static void main(String[] args) {
// 自然順序進行排序
TreeSet<Integer> ts = new TreeSet<Integer>();
// 添加元素
ts.add(1);
ts.add(18);
ts.add(23);
ts.add(22);
ts.add(17);
ts.add(24);
ts.add(19);
ts.add(18);
ts.add(2);
// 遍歷
//輸出: 1,2,17,18,19,22,23,24,
for (Integer i : ts) {
System.out.print(i+",");
}
}
結果爲: 1,2,17,18,19,22,23,24,
由於TreeSet可以實現對元素按照某種規則進行排序,所以我們這裏看到的是正常的排序。
3.2 如果是引用數據類型呢,比如自定義對象,又該如何排序呢?
3.2.1 錯誤示範
測試類代碼:
import java.util.TreeSet;
/**
* @author sunlee
* @date 2020/5/30 12:27
*/
public class MyCollectionTest {
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<Student>();
//創建元素對象
Student s1=new Student("sun",12);
Student s2=new Student("zhaoxin",2);
Student s3=new Student("manw",45);
Student s4=new Student("weien",78);
Student s5=new Student("sun",01);
Student s6=new Student("timo",100);
//將元素對象添加到集合對象中
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
//遍歷
for(Student s:ts){
System.out.println(s.getName()+"-----------"+s.getAge());
}
}
}
Student類:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
結果報錯:
原因分析:內部不知道該按照那一種排序方式排序,所以報錯。
解決方法:1.自然排序 2.比較器排序
3.2.2 自然排序
自然排序要進行以下操作:
1.Student類中實現 Comparable接口
2.重寫Comparable接口中的Compareto方法
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student o) {
//return -1; //-1表示放在紅黑樹的左邊,即逆序輸出
//return 1; //1表示放在紅黑樹的右邊,即順序輸出
//return o; //表示元素相同,僅存放第一個元素
//主要條件 姓名的長度,如果姓名長度小的就放在左子樹,否則放在右子樹
int num=this.name.length()-s.name.length();
//姓名的長度相同,不代表內容相同,如果按字典順序此 String 對象位於參數字符串之前,則比較結果爲一個負整數。
//如果按字典順序此 String 對象位於參數字符串之後,則比較結果爲一個正整數。
//如果這兩個字符串相等,則結果爲 0
int num1=num==0?this.name.compareTo(s.name):num;
//姓名的長度和內容相同,不代表年齡相同,所以還要判斷年齡
int num2=num1==0?this.age-s.age:num1;
//說白了就是按照:姓名長度->姓名字符順序->年齡 來排序
return num2;
}
}
測試類:
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<Student>();
//創建元素對象
Student s1=new Student("sun",12);
Student s2=new Student("zhaoxin",2);
Student s3=new Student("manw",45);
Student s4=new Student("weien",78);
Student s5=new Student("sun",01);
Student s6=new Student("timo",100);
//將元素對象添加到集合對象中
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
//遍歷
for(Student s:ts){
System.out.println(s.getName()+"-----------"+s.getAge());
}
}
運行結果:
sun-----------1
sun-----------12
manw-----------45
timo-----------100
weien-----------78
zhaoxin-----------2
3.2.2 比較器排序
比較器排序步驟:
1.單獨創建一個比較類,這裏以MyComparator爲例,並且要讓其繼承Comparator接口
2.重寫Comparator接口中的Compare方法
3.在主類的創建實例中使用自定義比較器
代碼如下:
Student類:
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
自定義的MyComparator比較器:
import java.util.Comparator;
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1,Student s2) {
// 姓名長度
int num = s1.getName().length() - s2.getName().length();
// 姓名內容
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
// 年齡
int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;
return num3;
}
}
測試類:
public static void main(String[] args) {
//主要加了這一句:new MyComparator(),其他不變
TreeSet<Student> ts=new TreeSet<Student>(new MyComparator());
//創建元素對象
Student s1=new Student("sun",12);
Student s2=new Student("zhaoxin",2);
Student s3=new Student("manw",45);
Student s4=new Student("weien",78);
Student s5=new Student("sun",01);
Student s6=new Student("timo",100);
//將元素對象添加到集合對象中
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
//遍歷
for(Student s:ts){
System.out.println(s.getName()+"-----------"+s.getAge());
}
}
運行結果:
sun-----------1
sun-----------12
manw-----------45
timo-----------100
weien-----------78
zhaoxin-----------2
4、三者的插入性能比較
HashSet、TreeSet、LinkedHashSet性能對比
代碼如下:
實體類 Dog:
class Dog implements Comparable<Dog> {
int size;
public Dog(int s) {
size = s;
}
public String toString() {
return size + "";
}
@Override
public int compareTo(Dog o) {
//數值大小比較
return size - o.size;
}
}
測試類 PerformanceTest :
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.TreeSet;
/**
* @author sunlee
* @date 2020/5/30 13:08
*/
public class PerformanceTest {
public static void main(String[] args) {
Random r = new Random();
HashSet<Dog> hashSet = new HashSet<Dog>();
TreeSet<Dog> treeSet = new TreeSet<Dog>();
LinkedHashSet<Dog> linkedSet = new LinkedHashSet<Dog>();
//hashSet---------------------------------------------------
long startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
int x = r.nextInt(10000 - 10) + 10;
hashSet.add(new Dog(x));
}
// end time
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("HashSet: " + duration);
//treeSet---------------------------------------------------
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
int x = r.nextInt(10000 - 10) + 10;
treeSet.add(new Dog(x));
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("TreeSet: " + duration);
//linkedSet---------------------------------------------------
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
int x = r.nextInt(10000 - 10) + 10;
linkedSet.add(new Dog(x));
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedHashSet: " + duration);
}
}
輸出結果:
HashSet: 9319822
TreeSet: 14542598
LinkedHashSet: 8672281
插入速度: HashSet>LinkHashSet>TreeSet
總結:TreeSet最慢,因爲內部進行排序。
二、Map
Map接口有三個比較重要的實現類,分別是HashMap、TreeMap和HashTable。
TreeMap:有序(基於紅黑樹對所有的key進行排序)、非線程安全、沒有調優選項(因爲該樹總處於平衡狀態)、不允許key值爲null
HashMap:無序、方法不同步、非線程安全、效率較高、允許null值(key和value都允許)
HashTable:無序、方法同步、線程安全、效率較低、不允許key值爲null
補充:
- Hashtable的父類是Dictionary,HashMap的父類是AbstractMap
- HashMap:適用於Map中插入、刪除和定位元素;對同步性或與遺留代碼的兼容性沒有任何要求時
- Treemap:適用於按自然順序或自定義順序遍歷鍵(key)。
三、擴容機制
四、數據結構
ArrayXxx:底層數據結構是數組,查詢快,增刪慢
LinkedXxx:底層數據結構是鏈表,查詢慢,增刪快
HashXxx:底層數據結構是哈希表。依賴兩個方法:hashCode()和equals()
TreeXxx:底層數據結構是二叉樹。兩種方式排序:自然排序和比較器排序