Java 集合概览

集合是Java中非常重要的一部分,熟练使用它是每个Java程序猿必备的技能。

1. 概览(图片下载(含Jude资源)

  • Collection

  • Map

2.对比

3.源码分析

下面从源码角度分析常见的几种数据结构添加、删除元素的过程。

ArrayList

  • ArrayList.add
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

从上面源码可以知道,ArrayList分为两步:1.扩容(如果需要扩容,每次增加1/2),2.赋值。

  • ArrayList.remove

    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

看完add方法,也可以知道get方法是按数组下标来取值的。而remove方法有两个,一个根据下标删除元素,另一个根据元素删除。这里讲解按下标删除。
1.检查索引是否越界
2.获得原位置上的旧值
3.判断是否删除的最后一个元素,不是则移动elementData数据,并将最后一个位置的元素置为空。
4.返回旧值

从上面的过程可以看出,ArrayList中的元素是非常紧凑的。

TreeSet与HashSet

TreeSet与HashSet内部都是用Map来保存数据,因此它们的添加、删除操作实际上是在Map上操作。它们内部的数据结构如图。

  • HashSet

  • TreeSet

HashMap

  • HashMap.add
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

准备知识:HashMap内部保存数据使用的散列表,冲突解决方法是链地址法,可参考博文(转):采用链地址法处理冲突构造哈希表

HashMap添加数据时分为以下步骤:

1. 调用hash(key),计算出Key可能的保存位置

2.判断table是否为空或者长度为0,是则调用resize()初始化

3.判断 table[(n-1)&hash]上是否有值,没有则赋值,有则采用链地址法解决hash值冲突。注:[(n-1)&hash即hash%(n-1),主要是为了防止hash值大于table的长度]。

4.判断变化后的size是否超出临界值,如果超出,则将table的大小增加一倍。注:这里modCount记录的是table被修改的次数,即添加,删除,修改数据时,modCount都会自增一 。

  • HashMap.remove
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
  final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

remove和add相似,大家可以自己试着分析一下。

4.总结

  • 从上面的分析可以看出,ArrayList不适合经常变化的情况,因为它增加或删除都会改变table,会造成很大的开销,但是它易于索引。
  • HashMap内部通过散列表来存储,修改和索引都比较方便,但是他内部数据是无序的;而TreeMap内部元素是有序的,但是因为它会维持一颗平衡树,因此修改的开销比HashMap大。
  • Set中元素是不可重复的,而List是可重复的。
  • ArrayList中元素的相对位置始终与添加的顺序一致。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值