Java中的Collection介绍

这篇博客介绍了Java中的Collection接口及其子接口,包括Set、List、Queue、Deque和Map。讲解了不同类型的集合特性,如Set不允许重复元素,List有序且允许重复,而Map则用于键值对映射。还对比了Collection与Array的区别,强调了Collection的动态大小和方法支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 

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:

InterfacesHash TableResizable ArrayTreeLinked ListHash Table+ Linked List
SetHashSet TreeSet LinkedHashSet
List ArrayList LinkedList 
Queue     
Deque ArrayDeque   
MapHashMap TreeMap LinkedHashMap

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值