Java 集合框架体系图ListMap
HashMapTreeMap 比较器
comparatorcomparable Set
HashSetTreeSet QueuePriorityQueueDequeueStackCollections
Java 集合框架体系图
Collection是除Map外其他集合类的根接口
List是一种有序列表,类似于数组
接口方法:
在末尾添加一个元素:boolean add(E e) 在指定索引添加一个元素:boolean add(int index, E e) 删除指定索引的元素:E remove(int index) 删除某个元素:boolean remove(Object e) 获取指定索引的元素:E get(int index) 获取链表大小(包含元素的个数):int size()
遍历
public class test1 {
public static void main(String[] args) {
List list= new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("-------");
for (String s : list) {
System.out.println(s);
}
System.out.println("-------");
for(Iterator it=list.iterator();it.hasNext();){
System.out.println(it.next());
}
}
}
List和Arry转化
- String[] strings = list.toArray(new String[list.size()]); - String[] arries = new String[3]; Listlist1 = Arrays.asList(arries);
要正确使用List的contains()、indexOf()这些方法,放入的实例必须正确覆写equals()方法,因为List内部并不是通过==判断两个元素是否相等,而是使用equals()方法判断两个元素是否相等,对于基本对象Java标准库定义的这些类已经正确实现了equals()方法
public boolean equals(Object o) {
if (o instanceof Person) {
Person p = (Person) o;
return this.name.equals(p.name) && this.age == p.age;
}
return false;
}
Map
遍历
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("apple", 123);
map.put("pear", 234);
map.put("banana", 456);
for (String s : map.keySet()) {
System.out.println(s);
System.out.println(map.get(s));
}
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
HashMap
HashMap内部使用了数组,初始大小为16,通过计算key的hashCode()并对15取余直接定位value所在的索引0-15;如果添加超过16个,HashMap会在内部自动扩容,每次扩容一倍,由于扩容会导致重新分布已有的key-value,所以频繁扩容对HashMap的性能影响很大,HashMap内部的数组长度总是2的n次方;在HashMap的数组中,若多个key散列到相同位置,则实际存储的不是一个实例,而是一个List,它可以包含多个Entry
要正确使用HashMap,作为key的类必须正确覆写equals()和hashCode()方法
TreeMap对key进行排序的Map;使用TreeMap时,放入的Key必须实现Comparable接口;如果作为Key的class没有实现Comparable接口,那么必须在创建TreeMap时同时指定一个自定义排序算法。String、Integer这些类已经实现了Comparable接口,因此可以直接作为Key使用。作为Value的对象则没有任何要求。
比较器 comparatorpublic class Hero{
public String name;
public int age;
public Hero() {
}
public Hero(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Hero{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
public class test1 {
public static void main(String[] args) {
ArrayList heroes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
heroes.add(new Hero("hero"+i,100-i));
}
System.out.println(heroes);
Comparator comparator = new Comparator() {
@Override
public int compare(Hero o1, Hero o2) {
if(o1.age >= o2.age){
return 1;
}else{
return -1;
}
}
};
Collections.sort(heroes,comparator);
System.out.println(heroes);
}
}
comparable
public class Hero implements Comparable{ public String name; public int age; public Hero() { } public Hero(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Hero{" + "name='" + name + ''' + ", age=" + age + '}'; } @Override public int compareTo(Hero o) { if(age import java.util.*; public class test1 { public static void main(String[] args) { ArrayListSet HashSetheroes = new ArrayList<>(); for (int i = 0; i < 10; i++) { heroes.add(new Hero("hero"+i,100-i)); } System.out.println(heroes); Collections.sort(heroes); System.out.println(heroes); } } 无序不重复,HashSet仅仅是对HashMap的一个简单封装
TreeSet有序不重复,使用TreeSet和使用TreeMap的要求一样,添加的元素必须正确实现Comparable接口,如果没有实现Comparable接口,那么创建TreeSet时必须传入一个Comparator对象
Queue常用方法
int size():获取队列长度; boolean add(E)/boolean offer(E):添加元素到队尾;add方法若队列已满抛异常,offer则返回false E remove()/E poll():获取队首元素并从队列中删除;remove方法如队列为空抛异常,poll返回null E element()/E peek():获取队首元素但并不从队列中删除,E element();E peek()
linkedList类实现了Queue接口,因此我们可以把linkedList当成Queue来用
inkedList即实现了List接口,又实现了Queue接口,在使用的时候,如果我们把它当作List,就获取List的引用,如果我们把它当作Queue,就获取Queue的引用public static void main(String[] args) { QueuePriorityQueuequ=new linkedList<>(); qu.offer("aaa"); qu.offer("bbb"); qu.offer("ccc"); System.out.println(qu.poll()); System.out.println(qu.poll()); System.out.println(qu.poll()); } public class TestQueue { public static void main(String[] args) { PriorityQueuequeue = new PriorityQueue<>(); queue.offer("aaa"); queue.offer("zzz"); queue.offer("ggg"); queue.offer("bbb"); while(queue.peek()!=null){ System.out.println(queue.poll()); } } } Dequeue
放入PriorityQueue的元素,必须实现Comparable接口,或者提供一个Comparator对象来判断两个元素的顺序,将comparator对象丢进priorityQueue的构造器中允许两头都进,两头都出,这种队列叫双端队列
常用方法
Queue Dequeue 添加元素到队尾 add(E e) / offer(E e) addLast(E e) / offerLast(E e) 取队首元素并删除 E remove() / E poll() E remove() / E poll() 取队首元素但不删除 取队首元素但不删除 E getFirst() / E peekFirst() 添加元素到队首 无 addLast(E e) / addFirst(E e) / offerFirst(E e) 取队尾元素并删除 无 addLast(E e) / E removeLast() / E pollLast() 取队尾元素但不删除 无 addLast(E e) / E getLast() / E peekLast() 总是调用xxxFirst()/xxxLast()以便与Queue的方法区分开
Deque是一个接口,它的实现类有ArrayDeque和linkedList
Stack在Java中,我们用Deque可以实现Stack的功能: 把元素压栈:push(E)/addFirst(E); 把栈顶的元素“弹出”:pop()/removeFirst(); 取栈顶元素但不弹出:peek()/peekFirst()Java的集合类并没有单独的Stack接口,当我们把Deque作为Stack使用时,注意只调用push()/pop()/peek()方法,不要调用addFirst()/removeFirst()/peekFirst()方法,这样代码更加清晰
CollectionsCollections是JDK提供的工具类,它提供了一系列静态方法,能更方便地操作各种集合
创建空集合
创建空List:ListemptyList() 创建空Map:Map emptyMap() 创建空Set:Set emptySet() 注意到返回的空集合是不可变集合,无法向其中添加或删除元素
创建单元素集合
创建一个元素的List:ListsingletonList(T o) 创建一个元素的Map:Map singletonMap(K key, V value) 创建一个元素的Set:Set singleton(T o) 要注意到返回的单元素集合也是不可变集合,无法向其中添加或删除元素
排序
Collections可以对List进行排序。因为排序会直接修改List元素的位置,因此必须传入可变Listpublic static void main(String[] args) { Listlist = new ArrayList<>(); list.add("apple"); list.add("pear"); list.add("orange"); // 排序前: System.out.println(list); Collections.sort(list); // 排序后: System.out.println(list); } 洗牌
Collections提供了洗牌算法,即传入一个有序的List,可以随机打乱List内部元素的顺序,效果相当于让计算机洗牌public static void main(String[] args) { Listlist = new ArrayList<>(); for (int i=0; i<10; i++) { list.add(i); } // 洗牌前: System.out.println(list); Collections.shuffle(list); // 洗牌后: System.out.println(list); }



