Java集合总结

1 集合分为两大类:Collection和Map

2 Collection

Collection有两个子类:List和Set。他们的区别,简单来说,List有序可重复,Set无序不可重复。(这里的顺序是指插入顺序)

2.1 List

特点:有序的集合,元素可以重复。

ArrayList和LinkedList,非线程安全,区别在于底层的实现上;Vector线程安全的。

2.1.1 ArrayList

底层以数组的形式存储元素,扩展时以当前数组大小的一半来扩展;

优点:查询快;缺点:插入和删除速度慢。

底层代码:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
	
	...
	
}

2.1.2 LinkedList

底层以双向链表的形式存储元素;

优点:插入和删除比较快;缺点:查询由于需要从第一个索引开始,所以慢。

LinkedList方法很多:

用于FIFO的addLast/removeFirst;

用于FILO的addFirst/removeLast;

双向遍历的:ListInterator(next()和previous())

底层代码:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    private transient Entry<E> header = new Entry<E>(null, null, null);
    private transient int size = 0;
	
	...
	
}

 private static class Entry<E> {
	E element;
	Entry<E> next;
	Entry<E> previous;
	
	...
	
}


2.1.3 Vector

线程安全的。

List的选择问题,Vector由于性能问题,一般不用,即使需要用到线程安全性,可以选择Collections.synchronizedCollection代替;如果集合的大小不怎么变化,可以选择ArrayList,如果大小确定,初始化ArrayList时把大小作为参数传递给构造函数

public ArrayList(int initialCapacity);

如果集合大小经常变化,使用LinkedList。注意,如果仅仅是为了保证顺序,都可以,因为他们本来就是有序的集合。

2.2 Set

特点:无序的集合,元素不能重复。

HashSet:基于散列表的集合,加紧散列表的元素要实现hashCode()。

LinkedhashSet:在HashSet的基础上,保证元素的加入顺序。

TreeSet:基于平衡树的数据结构。

Set的选择问题,HashSet是基于hash算法实现的,性能通常优于TreeSet;我们通常的选择是Hashset,但是当我们需要排序的功能时,使用TreeSet。

3 Map

是一种映射表集合:key-value。

HashMap:散列表的通用映射表。

LinkedHashMap:保证数据插入顺序。

TreeMap:基于平衡树的映射表。

HashTable:线程安全。

Map的选择问题,常用的是HashMap,如果需要保证插入顺序用LinkedHashMap,如果需要对数据排序,使用TreeMap;HashTable不常用,可以用Collections.synchronizedMap替代。

4 Collections

是java.util下的一个工具类,里面有各种对集合的静态方法。排序、2分查找、并发,等等。

这里说下创建线程安全的集合的方法:

Collection collection = Collections.synchronizedCollection(new ArrayList());
List list = Collections.synchronizedList(new ArrayList());
Set set = Collections.synchronizedSet(new HashSet());
Map map = Collections.synchronizedMap(new HashMap());

5 Collections.synchronizedCollection和传统的Vector等的区别

有待添加









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值