通常是java.util.Collection 的一个实例(虽然java.util.Map 正式也是集合框架的一部分)
虽然可以直接实现Collection接口,但通常客户端代码会使用其中一个子接口的实现:Set、List、Queue/Deque
这里是一些示例代码(左侧通常是一个接口,右侧是一个实现类)。
Sets 不存储重复项,它们的所有元素都是唯一的:
final Set<String> basicSet = new HashSet<String>();
basicSet.add("One");
basicSet.add("Two");
basicSet.add("One");
basicSet.add("Three");
System.out.println(basicSet.toString());
// Output: [Three, One, Two]
// (seemingly random order, no duplicates)
SortedSets 是按指定顺序存储元素的集合的特例:
final SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("One");
sortedSet.add("Two");
sortedSet.add("One");
sortedSet.add("Three");
System.out.println(sortedSet.toString());
// Output: [One, Three, Two]
// (natural order, no duplicates)
Lists 让您可以多次存储一个值并访问或修改插入顺序:
final List<String> strings = new ArrayList<String>();
strings.add("Two");
strings.add("Three");
strings.add(0, "One"); // add item to beginning
strings.add(3, "One"); // add item at position 3 (zero-based)
strings.add("Three");
strings.add(strings.size() - 1, "Two"); // add item at last-but-one position
System.out.println(strings);
// Output: [One, Two, Three, One, Two, Three]
还有一个定义列表的实用简写:
List<String> strings = Arrays.asList("One", "Two", "Three");
// this returns a different kind of list but you usually don't need to know that
等等
为了更好地理解,请阅读 Sun Java 教程(在线)中的 The Collections Trail,或 Maurice Naftalin 和 Philip Wadler 的 Java Generics and Collections