在Java里,有Collection和Collections。
Collection是一个interface (see java docs)。
Set, List, Queue, Dequeue也是interface,它们都是Collection的subinterface。而我们常用的Map并不继承Collection,它是和Collection并列关系interface。
Collection, Set, List, Map关系The collection interfaces are divided into two groups. The most basic interface, java.util.Collection, has the following descendants:
java.util.Set
java.util.SortedSet
java.util.NavigableSet
java.util.Queue
java.util.concurrent.BlockingQueue
java.util.concurrent.TransferQueue
java.util.Deque
java.util.concurrent.BlockingDeque
The other collection interfaces are based on java.util.Map and are not true collections. However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Map has the following offspring:
java.util.SortedMap
java.util.NavigableMap
java.util.concurrent.ConcurrentMap
java.util.concurrent.ConcurrentNavigableMap
而Collections是一个class (see java docs)。
常用的:
Collections.EMPTY_LIST
Collections.EMPTY_SET
Collections.EMPTY_MAP
Collections.singleton(T o) => return Set
Collections.singletonList(T o) => return List
Collections.singletonMap(K key, V value) => return Map
Collections.sort(List list)
比较:
-
Collectons.emptyList() v.s. Collections.EMPTY_LIST
Collections.EMPTY_LIST returns an old-style List
Collections.emptyList() uses type-inference and therefore returns List<T>
Collections.emptyList()是在Java 1.5的时候加进去的,我们一般倾向于用这个。这样我们就不用在code里面cast了。Collections.emptyList()内部就为我们进行cast。
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
-
Collections.emptyList() v.s. ImmutableList.of()
ImmutableList.of() (with no elements) internally delegates to a singleton, rather than recreating empty list instances.
Reference
https://docs.oracle.com/javase/7/docs/technotes/guides/collections/overview.html
网友评论