Java容器回顾

Java容器回顾

常用的容器

常用的容器

List 知识点

List 是按照一定顺序保存元素,他继承 Vector 对象, 用对象数组保存元素( Object[] ).

  • ArrayList : 擅长根据索引 index 随机访问元素, 元素的插入和删除效率很低。

在指定位置插入元素,会使用 add(int index, E element) 方法。 执行步骤如下:

  1. 检查index是否越界.
  2. 根据新的长度 size+1 检查是否容量足够,如果不够,按照 oldCapacity + (oldCapacity+1) 进行扩容。
  3. 用系统方法拷贝index之前和之后的元素,方法为 System.arraycopy(elementData, index, elementData, index + 1, size - index);
  4. 在index所在位置设置新元素 element. elementData[index] = element;
  5. 把ArrayList 的长度 size 加 1;

在指定位置添加元素的方法

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

在指定位置删除元素的方法

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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;
    }

Map 知识点

HashMap 是允许 key 为 null 的。 原因是 HashMap 根据 key 计算hash值,而hash值的计算方式如下:

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

可以看到,key 如果为null, 那么 hash值为0. 如果key不为null,就调用系统方法计算:

 public native int hashCode();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值