简化版ArrayList,顺序表
get(i) 时间复杂度 o(1)
add(i,v),remove(i) o(n)
ArrayList本质上就是一个数组
功能:
添加功能
指定位置添加
根据索引查询
实现迭代Itertable,可以for循环和迭代器
上代码:
public class SequestList<T> implements Iterable<T>{
//定义存储数组
private Object[] data;
//定义链表大小
private int size;
//无参数构造方法
public SequestList() {
data = new Object[10];
}
//添加
public void add(T t){
//判断是否需要扩容
if(data.length <= size){
//需要扩容
int oldCapacity = data.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
data = Arrays.copyOf(data, newCapacity);
}
data[size++] = t;
}
//指定位置添加数据
public void add(int index, T t){
if(index < 0 || index > size){
throw new RuntimeException("索引超限");
}
//判断是否需要扩容
if(data.length <= size){
//需要扩容
int oldCapacity = data.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
data = Arrays.copyOf(data, newCapacity);
}
//复制
System.arraycopy(data, index, data, index + 1, size - index);
data[index] = t;
size++;
}
/**
* 移出元素
*/
public void remove(int index){
if(index < 0 || index >= size){
throw new RuntimeException("索引超限");
}
//最后一个数
if(index == size -1){
data[index] = null;
}else{
System.arraycopy(data, index + 1, data, index, size - index);
data[size-1] = null;
}
size--;
}
public T get(int index) {
if(index < 0|| index > size){
throw new RuntimeException("索引下标超限");
}
return (T) data[index];
}
public static void main(String[] args) {
SequestList<String> sequestList = new SequestList<>();
sequestList.add("1");
sequestList.add("2");
sequestList.add("3");
sequestList.add("4");
sequestList.add("5");
// sequestList.remove(5);
sequestList.remove(4);
sequestList.remove(0);
sequestList.remove(1);
// for (String s : sequestList) {
// System.out.println(s);
// }
Iterator<String> iterator = sequestList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
//实现迭代器或者for循环
@Override
public Iterator<T> iterator() {
return new SIterator();
}
private class SIterator implements Iterator{
private int cur;
public SIterator(){
this.cur = 0;
}
@Override
public boolean hasNext() {
return cur < size;
}
@Override
public T next() {
return (T) data[cur++];
}
}
}