Array List简介
- ArrayList是以泛型方式实现的,使用时必须要先实例化
- ArrayList实现了RandomAccess接口,表明ArrayList支持随机访问
- ArrayList实现了Cloneable接口,表明ArrayList是可以clone的
- ArrayList实现了Serializable接口,表明ArrayList是支持序列化的
- 和Vector不同,ArrayList不是线程安全的,在单线程下可以使用,在多线程中可以选择Vector或者CopyOnWriteArrayList
- ArrayList底层是一段连续的空间,并且可以动态扩容,是一个动态类型的顺序表
实现一个 ArrayList
package ArrayList;
import java.util.Arrays;
public class MyArrayList {
public int[] elem;
public int usedSize;
public static final int DEFAULT_SIZE = 10;
public MyArrayList() {
this.elem = new int[DEFAULT_SIZE];
}
public void display(){
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
public int size() {
return this.usedSize;
}
public int get(int pos) {
checkGetIndex(pos);
return this.elem[pos];
}
public void set(int pos,int value) {
checkAddIndex(pos);
this.elem[pos] = value;
}
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind) {
return true;
}
}
return false;
}
public int indexOf(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind) {
return i;
}
}
return -1;
}
public void add(int data) {
resize();
this.elem[this.usedSize] = data;
this.usedSize++;
}
public void remove(int toRemove) {
int index = indexOf(toRemove);
if (index == -1) {
System.out.println("没找到");
}
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
}
public boolean isFull(){
return this.usedSize == DEFAULT_SIZE;
}
public void add(int pos,int data) {
checkAddIndex(pos);
resize();
for (int i = this.usedSize-1; i >= pos; i--) {
this.elem[i+1] = this.elem[i];
}
elem[pos] = data;
this.usedSize++;
}
public void clear() {
for (int i = 0; i < this.usedSize; i++) {
this.elem[i] = 0;
}
this.usedSize = 0;
}
private void checkAddIndex(int pos) {
if(pos < 0 || pos > this.usedSize) {
throw new IndexOutException("下标不合法");
}
}
private void checkGetIndex(int pos) {
if(pos < 0 || pos >= this.usedSize) {
throw new IndexOutException("下标不合法");
}
}
private void resize() {
if(this.isFull()){
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
}
}