1 顺序表
public class MyArrayList {
public int[] elem;
public int usedSize;
public static final int DEFAULT_CAPACITY = 5;
public MyArrayList(){
elem=new int[DEFAULT_CAPACITY];
}
}
2 顺序表中的方法
2.1 display(打印顺序表中的所有元素)
@Override
public class Main {
public void display() {
for (int i = 0; i < usedSize; i++) {
System.out.println(elem[i]+" ");
}
System.out.println();
}
2.2 add (添加元素)
@Override
public void add(int data) {
//判断是否满了 满了要扩容
if(isFull()){
elem = Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize]=data;
usedSize++;
}
@Override
public boolean isFull(){
return usedSize == elem[elem.length];
}
2.3 add (给pos位置添加一个元素)
从后往前 移动元素
当 i < pos 时放入元素
public void add(int pos, int data){
//1:pos位置的判断
checkPosOfAdd(pos);
if(isFull()){
elem = Arrays.copyOf(elem,2*elem.length);
}
for(int i = usedSize-1; i>=pos ; i--){
elem[i+1] = elem[i];
}
elem[pos] = data;
usedSize++;
}
private void checkPosOfAdd(int pos){
if(pos < 0 || pos > usedSize){
throw new PosException("pos位置为:"+ pos);
}
}
2.4 判断是否包含某个元素
//判断是否包含某个元素
public boolean contains(int toFind){
for (int i = 0; i < usedSize; i++) {
if(elem[i]==toFind){
return true;
}
}
return false;
}
2.5 查找下标
public int indesOf(int toFind){
for (int i = 0; i < usedSize; i++) {
if (elem[i] == toFind) {
return i;
}
}
return -1;
}
2.6 删除toRemove这个数字
@Override
public void remove(int toRemove){
if (isEmpty()){
throw new EmptyException("顺序表为空,不能删除");
}
int index = indexOf(toRemove); //查找下标
for (int i=index;i < usedSize;i++){
elem[i] =elem[i+1];
}
usedSize--;
}
3 ArrayList的遍历
1:
System.out.println(arrayList);
2: for
for (int i = 0;i<arrayList.size();i++){
System.out.print(arrayList.get(i)+" ");
}
System.out.println();
3: for-each
for (int x:arrayList){
System.out.print(x+" ");
}
System.out.println();
4:迭代器
Iterator<Integer> it =arrayList.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
5:迭代器2(专门用于打印表)
ListIterator<Integer> it =arrayList.listIterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
6:从后向前打印
ListIterator<Integer> it =arrayList.listIterator(arrayList.size());
while(it.hasPrevious()){
System.out.print(it.previous()+" ");
}
System.out.println();
4 ArratLisr扩容
4.1 检测是否真正需要扩容,如果是调用grow准备扩容
4.2 预估需要扩容的大小
初步预估按照1.5倍大小扩容 也可根据用户所需大小扩容
4.3 使用copyOf进行扩容