ArrayList
可變數組。List接口可以指向ArrayList實例化對象的引用,因此以下兩種聲明方式都可以。
List<Integer> arr = new ArrayList<Integer>();
//或者
ArrayList<Integer> arr = new ArrayList<Integer>();
常用方法:
add(E e) //將指定的元素添加到此列表的尾部
add(int index, E element) //將指定的元素插入此列表中的指定位置
contains(Object o) //如果此列表中包含指定的元素,則返回 true
get(int index) //返回此列表中首次出現的指定元素的索引,或如果此列表不包含元素,則返回 -1
isEmpty() //如果此列表中沒有元素,則返回 true
remove(int index) //移除此列表中指定位置上的元素
remove(Object o) //移除此列表中首次出現的指定元素(如果存在)
set(int index, E element) //用指定的元素替代此列表中指定位置上的元素
size() //返回此列表中的元素數
對List排序,可以用Colletions.sort()方法。Colletions是一個工具類。Colletions.sort()默認從小到大排序,如果要自定義排序可以實現comparator接口。
import java.util.*;
public class Test_List {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(4);
arr.add(3);
System.out.println(arr);
Collections.sort(arr, new MyCompare());
System.out.println(arr);
}
}
class MyCompare implements Comparator<Integer> {
public int compare(Integer arg0, Integer arg1) {
return arg1 - arg0; //從大到小排序
}
}
LinkedList
雙向鏈表,增刪效率高,改查效率低。還具有隊列,雙端隊列,棧的特性。和ArrayList用法幾乎一樣,下面是一些LinkedList特有的方法。
addFirst(E e) //將指定元素插入此列表的開頭
addLast(E e) //將指定元素添加到此列表的結尾
getFirst() //返回此列表的第一個元素
getLast() //返回此列表的最後一個元素
push(E e) //將元素推入此列表所表示的堆棧
pop() //從此列表所表示的堆棧處彈出一個元素
HashSet
集合內的元素不能重複,且無序。
Set<Integer> set = new HashSet<>();
常用方法:
add(E e)
contains(Object o) //如果此 set 包含指定元素,則返回 true
isEmpty()
remove(Object o)
size()
LinkedHashSet和TreeSet也是Set接口的實現類,二者都是有序的集合。TreeSet默認按照元素大小進行排序,而LinkedHashSet用鏈表維護元素的次序,按照插入順序排序。
HashMap
HashMap實現了Map接口,是鍵值對<K,V>的集合。鍵不能重複,一個鍵只能對應一個值。而一個值可以對應多個鍵。
Map<String, Integer> map = new HashMap<>();
常用方法:
put(K key, V value)
remove(Object key)
size()
isEmpty()
get(Object key) //返回指定鍵所映射的值;如果對於該鍵來說,此映射不包含任何映射關係,則返回 null
getOrDefault(Object key, V defaultValue) //JDK8新增,當Map集合中有這個key時,就使用這個key值
//如果沒有就使用默認值defaultValue
HashMap中的元素是無序的,而TreeMap和LinkedHashMap中的元素是有序的。
TreeMap根據key的自然排序(升序)進行排序,可以實現Comparator接口,重寫compare方法自定義排序。
Queue
Queue<Integer> q = new LinkedList<>();
常用方法:
offer(E e) //插入隊列
poll() //獲取並刪除隊頭
element() 或 peek()//獲取隊頭但不刪去
Stack
Stack<Integer> st = new Stack<>();
常用方法:
empty()
peek() //查看堆棧頂部的對象,但不從堆棧中移除它
pop()
push(E item)
PriorityQueue
優先隊列,默認升序排序。
PriorityQueue<Integer> pq = new PriorityQueue<>();
常用方法:
offer(E e)
peek()
poll() //獲取並移除此隊列的頭
size()
實現降序排序:
public class Test {
PriorityQueue<Integer> pq = new PriorityQueue<>(new MyCompare());
}
class MyCompare implements Comparator<Integer> {
public int compare(Integer a, Integer b) {
return b - a;
}
}