首页 > 编程语言 > 详细

表的数组实现

时间:2021-07-24 11:36:16      阅读:34      评论:0      收藏:0      [点我收藏+]

package com.original.algorithm.table;

import java.util.Iterator;

public class MyArrayList implements Iterable {
private static final int DEFAULT_SIZE = 10;

private int theSize;

private AnyType[] theItems;

public MyArrayList() {
    doClear();
}

public void clear() {
    doClear();
}

private void doClear() {
    theSize = 0;
    enSureCapacity(DEFAULT_SIZE);
}

public int size() {
    return theSize;
}

private void enSureCapacity(int capacity) {
    // 可加可不加校验
    if (capacity < theSize) {
        return;
    }
    AnyType[] old = theItems;
    theItems = (AnyType[]) new Object[capacity];
    for (int i = 0; i < size(); i++) {
        theItems[i] = old[i];
    }
}

public AnyType get(int idx) {
    if (idx < 0 || idx >= theSize) {
        throw new IndexOutOfBoundsException();
    }
    return theItems[idx];
}

public AnyType set(int idx, AnyType x) {
    if (idx < 0 || idx >= theSize) {
        throw new IndexOutOfBoundsException();
    }
    AnyType old = theItems[idx];
    theItems[idx] = x;
    return old;
}

public void add(AnyType x) {
    add(size(), x);
}

private void add(int idx, AnyType x) {
    // 判断是否需要扩容
    if (idx == size()) {
        enSureCapacity(size() * 2 + 1);
    }

    // 插入合适位置并移动数组 - 先移动数组
    for (int i = size(); i > idx; i--) {
        theItems[i] = theItems[i - 1];
    }
    theItems[idx] = x;
    theSize++;
}

public void remove(int idx) {
    // 删除 - 将需要删除的原始的前一位一直覆盖
    for (int i = idx; i < size() - 11; i++) {
        theItems[i] = theItems[i + 1];
    }
    theSize--;
}

@Override
public Iterator<AnyType> iterator() {
    // 主要学习数据类型的实现方式 暂不理会
    return null;
}

}

表的数组实现

原文:https://www.cnblogs.com/zyyanga/p/15054333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!