public class MyArrayList<E> {
Object[] array;// 数组
int size;// 数组中真实存在的元素个数
private static final int DEFAULT_ARRAY_SIZE = 10;
public MyArrayList() {
array = new Object[0];
}
//指定数组大小
public MyArrayList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
array = new Object[capacity];
}
//构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
public MyArrayList(Collection<? extends E> collection) {
Object[] a = collection.toArray();
//注意:这里的toArray有可能返回不是object的(参看源码)
if (a.getClass() != Object[].class) {
Object[] newArray = new Object[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
a = newArray;
//确保这个ArrayList 不会因为传入的集合因为外部的改动而改动
}
array = a;
size = a.length;
}
// 扩容
private static int newCapacity(int currentCapacity) {
int increntment = (currentCapacity < DEFAULT_ARRAY_SIZE / 2) ? DEFAULT_ARRAY_SIZE
: currentCapacity >> 1;
return currentCapacity + increntment;
}
// 增加
public boolean add(E e) {
Object[] a = array;
int s = size;
if (s == a.length) {
Object[] newArray = new Object[newCapacity(a.length)];
System.arraycopy(a, 0, newArray, 0, s);
array = a = newArray;
}
a[s] = e;
size++;
return true;
}
// 删除下表元素
public E remove(int index) {
Object[] a = array;
int s = size;
if (index > s) {
throw new IndexOutOfBoundsException();
}
E e = (E) a[index];
System.arraycopy(a, index + 1, a, index, --s - index);
a[s] = null;
size = s;
return e;
}
// 删除元素
public boolean remove(Object object) {
Object[] a = array;
int s = size;
if (object == null) {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
remove(i);
return true;
}
}
} else {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
remove(i);
return true;
}
}
}
return false;
}
// 修改
public E set(int index, E e) {
Object[] a = array;
int s = size;
if (index > s) {
throw new IndexOutOfBoundsException();
}
E oldE = (E) a[index];
a[index] = e;
return oldE;
}
// 查找首次出现的位置
public int indexOf(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
return i;
}
}
} else {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
return i;
}
}
}
return -1;
}
// 查找最后出现的位置
public int lastIndexOf(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = s - 1; i >= 0; i--) {
if (object.equals(a[i])) {
return i;
}
}
} else {
for (int i = s - 1; i >= 0; i--) {
if (a[i] == null) {
return i;
}
}
}
return -1;
}
// 获取
public E get(int index) {
Object[] a = array;
if (index > size) {
throw new IndexOutOfBoundsException();
}
E e = (E) a[index];
return e;
}
// 是否为空
public boolean isEmpty() {
return size == 0;
}
// 元素的个数
public int size() {
return size;
}
}
我所理解的ArrayList
最新推荐文章于 2024-06-24 10:10:33 发布