重温数据结构一

数据结构

数据结构:
数据之间存在的一个或者多种的特定的关系元素的集合!

分类

根据数据对象的数据元素之间的关系,分类为逻辑结构与物理结构
逻辑结构:

1.集合结构
2.线性结构
3.树形结构
4.图形结构

物理结构:

1.顺序存储结构:
    内存地址是连续的,比如:ArrayList
2.链式存储结构
    内存地址不连续,可以找到下一个节点,形成链,比如:LinkedList

顺序存储ArrayList

简单看一下ArrayList的源码,里面维护了一个Object的数组,每次增加或者删除元素都要移动后面的元素!

    /**
     * Default initial capacity. 默认数组的长度,java与Android可能会有差别
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    // 维护一个数组
    transient Object[] elementData;

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

下面看几个主要用到的函数,增删改查:

 public boolean add(E e) {
         // 检查容量,适当扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 给数组元素赋值
        elementData[size++] = e;
        return true;
    }


public E remove(int index) {
       //越界检查
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        modCount++;
        E oldValue = (E) elementData[index];
        //移动后面的元素
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                           numMoved);
        //置空元素,让GC回收
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

  public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        // 返回指定位置的元素
        return (E) elementData[index];
    }

大概就看到这里了!ArrayList的源码比较简单,就是操作一个成员数组!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值