Java中的Collection介绍

https://docs.oracle.com/javase/tutorial/collections/interfaces/index.html

Collection可以说是把多个元素组合在一起的一种对象。Java中的collection分为5大类。对于这6类分别有对应的interface:set/list/queue/deque/map interfaces。These interfaces allow collections to be manipulated independently of the details of their representation. 

Java中的Collection介绍_第1张图片

Collection是基类,它规定了一系列methods用来使用操作collection,因此collection的子类都可以使用这些基本的methods,而每个子类如Set interface又规定了针对Set的一系列methods。注意其中map并不是一个真正的collection。

Set — a collection that cannot contain duplicate elements. HashSet不保证每次枚举出来的顺序是一样的。LinkedHashSet可以保证顺序。

List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). 

Queue — a collection used to hold multiple elements prior to processing. Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. 

Deque — 和Queue一样,但Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-out). 

Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.

SortedSet — a Set that maintains its elements in ascending order. 

SortedMap — a Map that maintains its mappings in ascending key order. 

Array和collection的区别:

虽然array和collection都可以存储操作elements,但是二者是不同的:

  1. Arrays are fixed in size but Collections are dynamic in size.
  2. Arrays can hold only homogeneous elements but collections can hold both homogeneous and heterogeneous elements
  3. Arrays don't have ready made methods but collections have ready made data structures and methods.
  4. Arrays can hold both primitives and wrapper objects but collections can hold only objects.

在java中Arrays是一个类,但是由于Arrays总是实例化以后再使用很麻烦,因此Arrays提供的都是静态方法,且通常没有返回值。同时使用了private构造函数,让代码里不能实例化Arrays,只能直接使用静态方法。如下例:

int[] a = {9,6,9}; // 只能这样创建一个array,而不能实例化一个Arrays
Arrays.sort(a); //调用静态方法。

而我们常用的是ArrayList。

Implementation:

Interfaces Hash Table Resizable Array Tree Linked List Hash Table+ Linked List
Set HashSet   TreeSet   LinkedHashSet
List   ArrayList   LinkedList  
Queue          
Deque   ArrayDeque      
Map HashMap   TreeMap   LinkedHashMap

 

你可能感兴趣的:(Java基础知识)