Collection
List
- subList()所产生的列表的幕后就是初始列表,对返回列表的修改都会返回到初始列表中。如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Pets {
public static void main(String[] args) {
Random rand = new Random(47);
List<String> pets = new ArrayList<String>();
pets.add("One");
pets.add("Two");
pets.add("Three");
pets.add("Four");
pets.add("Five");
System.out.println(pets);
List<String> sub = pets.subList(1, 4);
System.out.println(sub);
Collections.shuffle(sub,rand);
System.out.println(sub);
List<String> copy = new ArrayList<String>(pets);
System.out.println(copy);// TODO 自动生成的方法存根
}
}
/*[One, Two, Three, Four, Five]
[Two, Three, Four]
[Three, Two, Four]
//[One, Three, Two, Four, Five]*/
可以在上面程序中看到sub的改变会使原队列发生变化。
迭代器
- 使用方法iterator()要求容器返回一个Iterator。Iterator将准备好返回序列的第一个元素
- 使用next()获得序列的下一个元素
- 使用hasNext()检查序列中是否还有元素
- 使用remove()将迭代器新进返回的元素删除。
- ListIterator功能比迭代器多,主要是因为有索引。
Iterator<Pet> it = pets.iterator();
while(it.hasNext()){
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
//其中Pet是一个类,pets是Pet类的一个List
LinkList
添加了可以用于栈、队列或双端队列的方法。
Stack
先进后出:push(),peek(),pop(),empty()
Set
- HashSet 无序,使用散列函数存储
- TreeSet 将元素存储在红-黑数据结构中
- LinkedHashList:使用散列所以查询速度快,使用链表来维护元素插入顺序
Queue
- 先进先出:offer(),peek(),poll(),
- PriorityQueue: 优先级队列
Map
示例:
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapOfList {
public static Map<Integer, List<String>> book =
new HashMap<>();
static {
book.put(1, Arrays.asList("One","one"));
book.put(2, Arrays.asList("Two","two"));
book.put(3, Arrays.asList("Three","three"));
book.put(4, Arrays.asList("Four","four"));
}
public static void main(String[] args) {
System.out.println("key" + book.keySet());
System.out.println("value" + book.values());
for(int i :book.keySet()) {
System.out.println(i + "has");
for(String s:book.get(i))
System.out.println(" " + s);
}// TODO 自动生成的方法存根
}
}
输出/*
key[1, 2, 3, 4]
value[[One, one], [Two, two], [Three, three], [Four, four]]
1has
One
one
2has
Two
two
3has
Three
three
4has
Four
four
*/