前言:ArrayList中有很多方法,我们只有深知这些方法是怎么实现的才能更好的使用,不用死记硬背
我们来一一实现(重写)
前提准备:我们需要先创建一个类,类中写ArrayList的内部结构组成
public class MyList implements IList {private int[] array;private int size;public static final int Defaulte_size = 2;public MyList() {this.array = new int[Defaulte_size];}
}
add(int data)
public void add(int data) {if (isFull()) array = Arrays.copyOf(array, 2 * array.length);//数组容量不够扩容array[size] = data;size++;}
add(int pos, int data)
public void add(int pos, int data) {//指定位置添加元素if(pos<0 || pos >size) {System.out.println("pos不合法");return ;}if (isFull())array = Arrays.copyOf(array, 2 * array.length);for (int i = size-1; i >pos ; i--) {array[i+1]=array[i];}array[pos]=data;size++;
contains(int toFind)
//查找当前元素 是否存在public boolean contains(int toFind) {if (array == null) return false;for (int i = 0; i < array.length; i++) {if (array[i] == toFind) return true;}return false;}
indexOf(int toFind)
//查找当前元素 的下标public int indexOf(int toFind) {if (array == null) return -1;else {for (int i = 0; i < array.length; i++)if (array[i] == toFind) return i;}return -1;}
get(int pos)
//返回下标元素public int get(int pos) {if (isEmpty() || pos < 0 || pos >=size) {System.out.println("pos不合法");return -1;}else return array[pos];}
set(int pos, int value)
//更新pos位置的值为valuepublic void set(int pos, int value) {if (isEmpty()|| pos < 0 || pos >= size) {System.out.println("pos不合法");return;}array[pos] = value;}
remove(int toRemove)
//删除toRemove这个数字public void remove(int toRemove) {int dex=indexOf(toRemove);if (isEmpty() || dex < 0 || dex >= size) { System.out.println("没有"+toRemove);return;}else {for (int i = dex + 1; i < size; i++) {array[i - 1] = array[i];}//如果删除最后一个元素,最后size--后可以被删除size--;}}
size()
public int size() {
//求表中元素个数return size;}
clear()
//清空顺序表public void clear() {size=0;}
display()
//打印顺序表元素public void display() {for (int i = 0; i <size ; i++) {System.out.print(array[i]+" ");}System.out.println();}
isFull()
//判断是否满了 满了要扩容public boolean isFull() {if (size==array.length)return true;return false;}
isEmpty()
//判断表是否为空
public boolean isEmpty() {return size==0;}
}
测试代码
public class Testmain {public static void main(String[] args) {MyList test =new MyList();test.add(1);test.add(2);test.add(3);test.remove(4);test.add(3,5);test.display();System.out.println(test.isFull());System.out.println(test.get(0));}
}