本讲内容:集合 collection
讲集合collection之前,我们先分清三个概念:
- colection 集合,用来表示任何一种数据结构
- Collection 集合接口,指的是 java.util.Collection接口,是 Set、List 和 Queue 接口的超类接口
- Collections 集合工具类,指的是 java.util.Collections 类。
SCJP考试要求了解的接口有:Collection , Set , SortedSet , List , Map , SortedMap , Queue , NavigableSet , NavigableMap, 还有一个 Iterator 接口也是必须了解的。
SCJP考试要求了解的类有: HashMap , Hashtable ,TreeMap , LinkedHashMap , HashSet , LinkedHashSet ,TreeSet , ArrayList , Vector , LinkedList , PriorityQueuee , Collections , Arrays
下面给出一个集合之间的关系图:
此图是一个网友自己整理的,大家想下载浏览的话可以在网址:http://blog.csdn.net/u010887744/article/details/50575735进行操作。图上标注很详细的。
我们这里说的集合指的是小写的collection,集合有4种基本形式,其中前三种的父接口是Collection。
- List 关注事物的索引列表
- Set 关注事物的唯一性
- Queue 关注事物被处理时的顺序
- Map 关注事物的映射和键值的唯一性
一、 Collection接口分析:
Collection接口是Set,List,和Queue接口的父接口。提供了多数集合常用的方法声明。包括 add()、remove()、contains() 、size() 、iterator() 等。
add(E e) | 将指定对象添加到集合中 |
remove(Object o) | 将指定的对象从集合中移除,移除成功返回true,不成功返回false |
contains(Object o) | 查看该集合中是否包含指定的对象,包含返回true,不包含返回flase |
size() | 返回集合中存放的对象的个数。返回值为int |
clear() | 移除该集合中的所有对象,清空该集合。 |
iterator() | 返回一个包含所有对象的iterator对象,用来循环遍历 |
toArray() | 返回一个包含所有对象的数组,类型是Object |
toArray(T[] t) | 返回一个包含所有对象的指定类型的数组 |
我们在这里只举一个把集合转成数组的例子,因为Collection本身是个接口所以,我们用它的实现类ArrayList做这个例子:
@Test
public void javaCollectionDemo(){
String a = "a";
String b = "b";
String c = "c";
//声明一个List数组
Collection list = new ArrayList<String>();
list.add(a);
list.add(b);
list.add(c);
//调用collection的toArray()方法将list转换成array;
String [] array = (String[]) list.toArray(new String[1]);
//输出测试
for(String s: array){
System.out.print(s+",");
}
}
输出的结果显而易见:
1、 Java Collection接口的源码解析:
①、 接口的定义:
public interface Collection<E> extends Iterable<E>
1)、接口定义为泛型的(基本上Java中的所有接口都定义成泛型的,因为具体不知道这个接口具体用到什么数据类型上,故定义为泛型最佳)。
、接口继承了Iterable作为父接口。网上有文章这样解释到:"Iterable接口是Java中最顶级的接口之一,Collection接口继承了Iterable接口,因此Collection子类就必须实现Iterable接口的方法。而且只有继承了Iterable接口的类才能使用新的For循环"
以下分享以下Iterable接口的源码:
package java.lang;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
/**
* Implementing this interface allows an object to be the target of
* the "for-each loop" statement. See
* <strong>
* <a href="{@docRoot}/../technotes/guides/language/foreach.html">For-each Loop</a>
* </strong>
*
* @param <T> the type of elements returned by the iterator
*
* @since 1.5
* @jls 14.14.2 The enhanced for statement
*/
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator();
/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
/**
* Creates a {@link Spliterator} over the elements described by this
* {@code Iterable}.
*
* @implSpec
* The default implementation creates an
* <em><a href="Spliterator.html#binding">early-binding</a></em>
* spliterator from the iterable's {@code Iterator}. The spliterator
* inherits the <em>fail-fast</em> properties of the iterable's iterator.
*
* @implNote
* The default implementation should usually be overridden. The
* spliterator returned by the default implementation has poor splitting
* capabilities, is unsized, and does not report any spliterator
* characteristics. Implementing classes can nearly always provide a
* better implementation.
*
* @return a {@code Spliterator} over the elements described by this
* {@code Iterable}.
* @since 1.8
*/
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
3)、Collection接口的方法:
二、 几个重要接口和类的介绍:
1、 List接口的分析学习:
List关心的就是索引,与其他的集合相比较,List特有的就是和索引相关的一些方法:get(int index) 、 add(int index,Object o),indexOf(Object o) 。
①、List接口的方法分析:
以上为List接口里面的全部方法。但是大部分的方法都是来自于父接口Collection的,真正属于List接口分方法只有几个。
从Java的API中可以在很明确的了解到。接口List有两个父接口分别是:Collection<E>, Iterable<E>.
所有已知的实现类主要有:AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList,
但是在平时的开发中用的相对比较多的实现类通常只有以下几种:
1)、 ArrayList:可以理解成是一个可以增长的数组,其提供了快速迭代和快速随机访问的能力:
*、ArrayList在Java8中的定义为:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Class ArrayList<E>
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractList<E>
-
- java.util.ArrayList<E>
-
-
All Implemented Interfaces:
- Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
-
Direct Known Subclasses:
- AttributeList, RoleList, RoleUnresolvedList
以上是和ArrayList相关的层级关系和实现的接口,继承的类关系。ArrayList的特点是在内存中占用连续的一块存储区域。
2)、 LinkedList: 该实现类的元素之间的实现是以双向链表实现的,特点是当要对这个List进行快速插入和删除时性能高效。它在内存中的存储区域在内存中可以不是连续的(可以由List的双向引用指定List的前驱和后继)
*、LinkedList的类结构:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
Class LinkedList<E>
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractList<E>
-
- java.util.AbstractSequentialList<E>
-
- java.util.LinkedList<E>
-
-
Type Parameters:
-
E
- the type of elements held in this collection
-
All Implemented Interfaces:
- Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>
-
以上是和LinkedList相关的层级关系和实现的接口,继承的类关系。
3)、Vector: 这个实现类是ArrayList的线程安全版本。性能相较ArrayList较差,使用较少。
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
2、Set接口
Set关心唯一性,它不允许重复。HashSet 当不希望集合中有重复值,并且不关心元素之间的顺序时可以使用此类。
LinkedHashset 当不希望集合中有重复值,并且希望按照元素的插入顺序进行迭代遍历时可采用此类。
TreeSet 当不希望集合中有重复值,并且希望按照元素的自然顺序进行排序时可以采用此类。(自然顺序意思是某种和插入顺序无关,而是和元
素本身的内容和特质有关的排序方式,譬如“abc”排在“abd”前面。)
LinkedList 同样实现了Queue接口,可以实现先进先出的队列。
PriorityQueue 用来创建自然排序的优先级队列。番外篇中有个例子http://android.yaohuiji.com/archives/3454你可以看一下。
HashMap 当需要键值对表示,又不关心顺序时可采用HashMap。
Hashtable 注意Hashtable中的t是小写的,它是HashMap的线程安全版本,现在已经很少使用。
LinkedHashMap 当需要键值对,并且关心插入顺序时可采用它。
3、Queue接口
Queue用于保存将要执行的任务列表。LinkedList 同样实现了Queue接口,可以实现先进先出的队列。
PriorityQueue 用来创建自然排序的优先级队列。番外篇中有个例子http://android.yaohuiji.com/archives/3454你可以看一下。
4、Map接口
Map关心的是唯一的标识符。他将唯一的键映射到某个元素。当然键和值都是对象。HashMap 当需要键值对表示,又不关心顺序时可采用HashMap。
Hashtable 注意Hashtable中的t是小写的,它是HashMap的线程安全版本,现在已经很少使用。
LinkedHashMap 当需要键值对,并且关心插入顺序时可采用它。
TreeMap 当需要键值对,并关心元素的自然排序时可采用它。
以上知识只是粗略的了解以下Java中的集合类和接口,在接下来的篇幅中会分别详细了解每一块的具体使用和使用场景。