package com.kgc;
public class SxtArrayList02<E> {
private Object[] elementData;
private int size;
// 默认长度
private static final int DEFAULT_CAPACITY = 10;
// 无参构造
public SxtArrayList02() {
elementData = new Object[DEFAULT_CAPACITY];
}
// 有参构造
public SxtArrayList02(int capacity) {
if (capacity < 0) {
throw new RuntimeException("容量的大小不能为负数");
} else if (capacity == 0) {
elementData = new Object[DEFAULT_CAPACITY];
} else {
elementData = new Object[capacity];
}
}
public int size() {
return size;
}
public boolean isEmpty() {
return size==0?true:false;
}
public void add(E element) {
// 什么时候扩容??
if (size == elementData.length) {
// 怎么扩容
Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];// 10-->10+10/2
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
elementData[size++] = element;
}
public E get(int index) {
checkRange(index);
return (E) elementData[index];
}
public void set(E element, int index) {
checkRange(index);
elementData[index] = element;
}
public void checkRange(int index) {
// 索引合法判断[0,size)
if (index < 0 || index > size - 1) {
// 不合法
throw new RuntimeException("索引不合法:" + index);
}
}
public void remove(E element) {
//element,将它和所有元素挨个比较,获得第一个比较为true的,返回。
for(int i = 0;i<size;i++) {
if(element.equals(get(i))) {//容器中所有的比较操作,都是用的equals而不是==
//将该元素从此处移除
remove(i);
}
}
}
public void remove(int index) {
//a,b,c,d,e,f,g,h
//a,b,c,e,g,f,h
int numMoved = elementData.length-index-1;
if(numMoved>0) {
System.arraycopy(elementData, index+1, elementData, index, numMoved);
}
elementData[--size] = null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(elementData[i] + ",");
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
public static void main(String[] args) {
}
}
手工实现ArrayList
最新推荐文章于 2022-05-26 08:54:16 发布