手动实现java常用的容器-arrayList
手动实现java常用的容器-arrayList
(方法只是模拟java源码,效率没有底层源码高,纯属学习熟悉底层源码)
package com.alan.alanarraylist;
/**
* author Mr.ALan
* DESCRIPTION
* create 2019/4/11/
*/
public class AlanArrayList<E> {
// 底层存放数据的容器
private E[] table;
// 用于初始化默认大小
public static final int DEFAULT_SIZE = 10;
// 记录有效的数据个数
private int size;
// 默认构造
public AlanArrayList() {
table = (E[]) new Object[10];
}
// 带参数构造
public AlanArrayList(int n) {
table = (E[]) new Object[n];
}
// 检查索引
private void checkIndex(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("数组索引越界异常");
}
}
// 数组增长 当数组的位置不够是增长为原本的1.5倍
private void grow() {
if (size == realSize()) {
E[] tempTable = (E[]) new Object[size + (size >> 1)];
System.arraycopy(table, 0, tempTable, 0, table.length);
table = tempTable;
}
}
// 添加元素
public void add(E element) {
grow();
table[size] = element;
size++;
}
// 在指定的索引添加元素
public void add(int index, E element) {
checkIndex(index);
grow();
System.arraycopy(table, index, table, index + 1, size - index);
table[index] = element;
size++;
// 0 1 2 3
// aa bb cc
// aa bb cc
}
// 通过索引查找元素
public E get(int index) {
checkIndex(index);
// 修改返回值
return table[index];
}
// 通过索引删除元素
public void remove(int index) {
checkIndex(index);
System.arraycopy(table, index + 1, table, index, size - 1 - index);
table[size - 1] = null;
size--;
// 0 1 2 3
// aa bb cc
// aa cc
}
// 通过对象删除元素
public void remove(E element) {
int tempIndex = -1;
for (int i = 0; i < size; i++) {
if (element.equals(table[i])) {
tempIndex = i;
break;
}
}
if (tempIndex != -1) {
remove(tempIndex);
}
}
// 清空容器
public void clear() {
table = (E[]) new Object[DEFAULT_SIZE];
size = 0;
}
// 重写toString方法
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
if (size == 0) {
sb.append("]");
return sb.toString();
} else {
for (int i = 0; i < size; i++) {
sb.append(table[i] + "").append(",");
}
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
// 返回有效的元素个数
public int size() {
return size;
}
// 返会真实的容器容量大小
public int realSize() {
return table.length;
}
// 判断是否为空
public boolean isEmpty() {
return size == 0;
}
}
ps:纯属学习交流,若有错误欢迎纠错