Java Collection类

Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。Java SDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection的“子接口”如List和Set。

语法

public interface Collection<E> extends Iterable<E> {}

它是一个接口,是高度抽象出来的集合,它包含了集合的基本操作:添加、删除、清空、遍历(读取)、是否为空、获取大小、是否保护某元素等等。

方法

boolean add(E e) 
    确保此 collection 包含指定的元素(可选操作)。 
boolean addAll(Collection c) 
    将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。 
void clear() 
    移除此 collection 中的所有元素(可选操作)。 
boolean contains(Object o) 
    如果此 collection 包含指定的元素,则返回 true。 
boolean containsAll(Collection c) 
    如果此 collection 包含指定 collection 中的所有元素,则返回 true。 
boolean equals(Object o) 
    比较此 collection 与指定对象是否相等。 
int hashCode() 
    返回此 collection 的哈希码值。 
boolean isEmpty() 
    如果此 collection 不包含元素,则返回 true。 
Iteratoriterator() 
    返回在此 collection 的元素上进行迭代的迭代器。 
boolean remove(Object o) 
    从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。 
boolean removeAll(Collection c) 
    移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。 
boolean retainAll(Collection c) 
    仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。 
int size() 
    返回此 collection 中的元素数。 
Object[] toArray() 
    返回包含此 collection 中所有元素的数组。
T[] toArray(T[] a) 
    返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。

iterator接口

不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子,使用该迭代子即可逐一访问Collection中每一个元素。iterator方法如下:

boolean	hasNext()
	如果仍有元素可以迭代,则返回 true。
E next()
	返回迭代的下一个元素。
void remove()
	从迭代器指向的集合中移除迭代器返回的最后一个元素(可选操作)。

Iterator实例

Iterator it = collection.iterator(); // 获得一个迭代子
while(it.hasNext()) {
	Object obj = it.next(); // 得到下一个元素
}

继承体系

Collection
    |-----List  有序(存储顺序和取出顺序一致),可重复
        |----ArrayList ,线程不安全,底层使用数组实现,查询快,增删慢,效率高。
        |----LinkedList , 线程不安全,底层使用链表实现,查询慢,增删快,效率高。
        |----Vector , 线程安全,底层使用数组实现,查询快,增删慢,效率低。每次容量不足时,默认自增长度的一倍(如果不指定增量的话),如下源码可知
    |-----Set   元素唯一一个不包含重复元素的 collection。更确切地讲,set 不包含满足 e1.equals(e2) 的元素对 e1 和 e2,并且最多包含一个 null 元素。
        |--HashSet 底层是由HashMap实现的,通过对象的hashCode方法与equals方法来保证插入元素的唯一性,无序(存储顺序和取出顺序不一致),。
            |--LinkedHashSet 底层数据结构由哈希表和链表组成。哈希表保证元素的唯一性,链表保证元素有序。(存储和取出是一致)
        |--TreeSet 基于 TreeMap 的 NavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。 元素唯一。

Java Collection类继承

Collection包含了List和Set两大分支:
1)、List是一个有序的队列,每一个元素都有它的索引,第一个元素的索引值是0。List的实现类有LinkedList、ArrayList、Vector和Stack。
(1)、LinkedList实现了List接口,允许元素为空,LinkedList提供了额外的get,remove,insert方法,这些操作可以使LinkedList被用作堆栈、队列或双向队列。
LinkedList并不是线程安全的,如果多个线程同时访问LinkedList,则必须自己实现访问同步,或者另外一种解决方法是在创建List时构造一个同步的List。
(2)、ArrayList  实现了可变大小的数组,允许所有元素包括null,同时ArrayList也不是线程安全的。
(3)、Vector类似于ArrayList,但Vector是线程安全的。
(4)、Stack继承自Vector,实现一个后进先出的堆栈。
2)、set是一个不允许有重复元素的集合。set的实现类有Hashset和Treeset。HashSet依赖于HashMap,实际上是通过HashMap实现的;TreeSet依赖于TreeMap,通过TreeMap来实现的。

总结

(1)如果涉及到堆栈,队列等操作,应该考虑用List;对于需要快速插入,删除元素,应该使用LinkedList;如果需要快速随机访问元素,应该使用ArrayList。
(2)如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高;如果多个线程可能同时操作一个类,应该使用同步的类。
(3)要特别注意对哈希表的操作,作为key的对象要正确复写equals和hashCode方法。
(4)尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。

例子

public class CollectionReview {
    public static void main(String[] args) {
        test1();
    }
    private static void test1() {
        Collection<String> collection = new Vector<>();
        collection.add("gogogo");
        collection.add("pap");
        collection.add("niko");
        collection.add("kitty");

        Collection<String> coll = new ArrayList<>();
        coll.add("niko");
        coll.add("kitty");
        coll.add("pecuyu");

        // collection.clear(); // 清空集合
         //System.out.println(collection.isEmpty()); // 集合是否为空

        // int size = collection.size(); // 获取集合大小
        // System.out.println(size);  

        // boolean contains = collection.contains("niko"); // 是否包含另一个元素
        // System.out.println(contains);
        //boolean containsAll = collection.containsAll(coll); //是否完全包含另一个集合
        //System.out.println(containsAll);

        // collection.remove("kitty");   // 删除第一个匹配项,删除了匹配项则返回true
        // boolean removeAll = collection.removeAll(coll);  // 删除与指定集合有交集的部分,原集合有改变就返回true
        // System.out.println(removeAll);

        //boolean retainAll = collection.retainAll(coll);// 保留与指定集合有交集的部分,原集合有改变就返回true
        //System.out.println(retainAll);

    // iterator 迭代器, 方式1
        Iterator<String> iterator = collection.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next()+" ");
        }
        System.out.println("\n"+"-------------------");

    // 方式2 ,for循环完iterator1就会被销毁,节约内存提高效率
        for (Iterator<String> iterator1 = collection.iterator(); iterator1.hasNext(); ) {
            System.out.print(iterator1.next()+" ");

        }
        System.out.println("\n"+"-------------------");


        Object[] array = collection.toArray();  // 转化为object数组
        for (Object string : array) {
            System.out.print(string+" ");
        }
        System.out.println("\n"+"-------------------");
        String[] arr=new String[collection.size()];
        String[] array2 = collection.toArray(arr);  // 指定要转化的数组类型
        for (String string : array2) {
            System.out.print(string+" ");
        }
    }




精彩推荐