什么是java集合? [英] What is a java collection?
问题描述
我想知道:Java中的集合是什么?
I want to know: What is a collection in Java?
推荐答案
通常是 java.util.Collection (虽然 java.util.Map 正式也是集合框架的一部分)
Usually an instance of java.util.Collection (although java.util.Map is officially also a part of the collections framework)
虽然Collection接口可以直接实现,但通常客户端代码将使用一个子接口的实现:设置,列表,队列 / Deque
Although the Collection interface can be implemented directly, usually client code will use an implementation of one of the sub interfaces: Set, List, Queue / Deque
下面是一些示例代码(左侧)通常见界面,右侧有一个实现类)。
Here is some sample code (on the left side you will usually see an interface and on the right side an implementation class).
集合不存储重复项,其所有元素都是唯一的:
Sets don't store duplicates, all of their elements are unique:
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 是以特定顺序存储元素的集合的特殊情况:
SortedSets are a special case of sets that store elements in a specified order:
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 let you store a value multiple times and access or modify insertion order:
final List<String> strings = new ArrayList<String>();
strings.add("Two");
strings.add("Three");
strings.add(0, "One");
strings.add(3, "One");
strings.add("Three");
strings.add(strings.size() - 1, "Two");
System.out.println(strings);
// Output: [One, Two, Three, One, Two, Three]
还有用于定义列表的实际速记:
There is also a practical shorthand for defining a list:
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教程(在线)的Collections Trail ,或 Java通用和收藏 by Maurice Naftalin和Philip Wadler
To get a better understanding, read The Collections Trail from the Sun Java Tutorial (online), or Java Generics and Collections by Maurice Naftalin and Philip Wadler
这篇关于什么是java集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!