自己实现一个简单的ArrayList
Posted esrevinud
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自己实现一个简单的ArrayList相关的知识,希望对你有一定的参考价值。
参考接口
public interface myList<T> {
void add(T element);
void add(Integer index, T element);
T remove(Integer index);
Boolean contains(T element);
Integer size();
Integer indexOf(T element);
Integer lastIndexOf(T element);
void set(Integer index, T element);
T get();
T get(Integer index);
Boolean clear();
Boolean isEmpty();
}
实现代码
package learn.code.list;
public class MyArrayList<T> implements myList<T> {
private T[] core;
private int size;
private void resize(int capacity) {
T[] newCore = (T[]) new Object[capacity];
for (int i = 0; i < core.length; i ++) {
newCore[i] = core[i];
}
core = newCore;
}
public MyArrayList () {
this(10);
}
public MyArrayList (int capacity) {
core = (T[]) new Object[capacity];
size = 0;
}
@Override
public void add(T element) {
if (size == core.length) {
// 扩容原先的2倍
this.resize(core.length * 2);
}
core[size] = element;
size ++;
}
// 指定下标位置插入,不能跳跃当前最后的下标
@Override
public void add(Integer index, T element) {
if (index < 0 || index >= core.length) {
throw new IndexOutOfBoundsException("下标不能小于0");
}
if (index >= core.length) {
throw new IndexOutOfBoundsException("下标超出当前数组");
}
core[index] = element;
size ++;
}
@Override
public T remove(Integer index) {
T removeTarget = core[index];
for (int i = index; i < (size - 1); i ++) {
core[index] = core[index + 1];
}
size --;
return removeTarget;
}
public T removeLast() {
return remove(size - 1);
}
public T removeFirst() {
return remove(0);
}
@Override
public Boolean contains(T element) {
for (T e : this.core) {
if (e == element) {
return true;
}
}
return false;
}
@Override
public Integer size() {
return this.size;
}
// 找到就返回下标,没找到就返回-1
@Override
public Integer indexOf(T element) {
for (int i = 0; i < core.length; i ++) {
if (core[i] == element) {
return i;
}
}
return -1;
}
// indexOf的逆序版
@Override
public Integer lastIndexOf(T element) {
for (int i = core.length - 1; i >= 0; i --) {
if (core[i] == element) {
return i;
}
}
return -1;
}
@Override
public void set(Integer index, T element) {
if (index < 0 || index >= core.length) {
throw new IndexOutOfBoundsException("下标不能小于0");
}
if (index >= core.length) {
throw new IndexOutOfBoundsException("下标超出当前数组");
}
core[index] = element;
}
// 软删除, 不删除实际元素
@Override
public Boolean clear() {
size = 0;
return null;
}
@Override
public Boolean isEmpty() {
return size == 0;
}
@Override
public T get() {
return core[size - 1];
}
@Override
public T get(Integer index) {
return core[index];
}
public static void main(String[] args) {
MyArrayList<Integer> arr = new MyArrayList<>();
for (int i = 0; i < 10; i ++) {
arr.add(10 - i);
}
// arr.set(0, 666);
// arr.remove(2);
arr.removeLast();
arr.clear();
for (int i = 0; i < arr.size(); i ++) {
System.out.println(arr.get(i));
}
System.out.println(arr.isEmpty());
}
}
以上是关于自己实现一个简单的ArrayList的主要内容,如果未能解决你的问题,请参考以下文章