本文主要实现了顺序表,顺序的表主要方法皆有涵盖,例如获取顺序表大小,判断表是否为空,清除表中所有元素,清除指定索引的元素,修改指定索引上的元素值,获取指定索引的元素值,在指定索引上添加元素。本文还实现了简单的迭代器
在C语言中我们实现顺序表我们采用的是结构体,那么在java里面,一个对象就和结构体非常的相似,结构体的成员就是java类的成员变量
实现一个动态的顺序表首先需要一个可以存储任意类型的数组,并且数组有初始化容量,并且还需要有一个变量来记录顺序表中元素的个数
private static final int DEFAULT_CAPACITY=10;//默认容量
private AnyType[] item;//顺序表存储
private int theSize;//记录当前元素表的元素个数
代码如下
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList<AnyType> implements Iterable<AnyType>{
private static final int DEFAULT_CAPACITY=10;//默认容量
private AnyType[] item;//顺序表存储
private int theSize;//记录当前元素表的元素个数
//返回当前顺序表的元素个数
public int size(){
return theSize;
}
//初始化,给成员变量赋值,使其不为null
public MyArrayList() {
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
//初始化顺序表,由外部提供数组大小,使得扩容次数减少,减少浪费
public MyArrayList(int capacity){
theSize=0;
ensureCapacity(capacity);
}
//判断当前顺序表是否为空
public boolean isEmpty(){
return theSize==0;
}
//清空当前顺序表内的所有元素
public void clearAll(){
theSize=0;
item=(AnyType[])new Object[DEFAULT_CAPACITY];//重新初始化即可清除以前的所有元素
}
//清空指定的索引的元素(数组位置)
public AnyType remove(int index){
if(index>theSize||index<0){//判断给定的索引是否存在问题
throw new ArrayIndexOutOfBoundsException();
}
AnyType removeItem=item[index];
for(int i=index;i<item.length;i++){
item[i]=item[i+1];//遍历前移,将被删除的元素的位置补上
}
theSize--;
return removeItem;
}
//设置指定索引的元素位置,返回被设置的索引位置上的元素值
public AnyType set(int index,AnyType value){
if(index>theSize||index<0){
throw new ArrayIndexOutOfBoundsException();
}
AnyType oldValue=item[index];
item[index]=value;
return oldValue;
}
//获取指定索引位置上的元素
public AnyType get(int index){
if(index>theSize+1||index<0){
throw new ArrayIndexOutOfBoundsException();
}
return item[index];
}
//在指定位置上添加元素
public void add(int index,AnyType value){
if(index<0||index>size()+1){
throw new ArrayIndexOutOfBoundsException("位置错误");
}
if(theSize==item.length){
ensureCapacity(size()*2+1);//数组扩容,+1的原因是防止size=0的情况,这里仅做简单的扩容,当数组非常大的时候应采用更好的算法
//并且频繁的指数级的扩容一般会造成空间的浪费
}
item[index]=value;
for(int i=size();i>index;i--){
item[i]=item[i+1];
}
theSize++;
}
//数组扩容
public void ensureCapacity(int newCapacity){
if(newCapacity<theSize){//判断新的容量是否大于当前最大元素,一般情况下只有数组满了才会进行扩容
return;
}
if(item==null){
item=(AnyType[]) new Object[DEFAULT_CAPACITY];//防止出现空指针的情况
}
AnyType[] old=item;
item=(AnyType[]) new Object[newCapacity];
for(int i=0;i<old.length;i++){
item[i]=old[i];
}
}
@Override
//仅做简单的迭代器实现
public Iterator<AnyType> iterator() {//实现Iterable接口必须实现的方法,该方法返回一个自己编写的迭代器
return new ArrayListItertor(this);
}
private class ArrayListItertor implements Iterator<AnyType>{//自己编写的迭代器要实现Iterator接口
private int current=0;//迭代器当前所指向的元素
private MyArrayList<AnyType> theList;
ArrayListItertor(MyArrayList<AnyType> list){
theList=list;
}
public boolean hasNext(){//判断是否有下一个元素
return current<theList.size();
}
public AnyType next(){//指向下一个元素
if(!hasNext()){
throw new NoSuchElementException();
}
return item[current++];
}
//删除迭代器当前指向的元素
public void remove(){
MyArrayList.this.remove(--current);
}
}
}
第一次自己实现顺序表,做个记录