表的数组实现

2021/7/24 6:05:34

本文主要是介绍表的数组实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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;
}

}



这篇关于表的数组实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程