import java.util.Arrays;
class List<T>{
private static int capacity = 5;
private int currentsize;
private T[] elem;
//不带参数的初始化(默认初始化大小为5)
public List() {
this.elem = (T[]) new Object[capacity];
this.currentsize = 0;
}
//设置容量的初始化
public List(int num) {
this.elem = (T[]) new Object[num];
this.currentsize = 0;
}
//检查容量
private boolean checkcapacity() {
if (this.currentsize == capacity) {
return false;
} else return true;
}
//扩容(2倍扩容)
public void spreadcapacity() {
this.elem = Arrays.copyOf(
this.elem, 2 * this.elem.length);
}
//检查位置是否合法
public void checkpos(int i){
if(i < 0 || i > currentsize){
throw new YiChang(i+"位置不合法");
}
}
//向数组最后增添一个元素
public void addlast(T e) {
if (!this.checkcapacity()) {
this.spreadcapacity();
}
this.elem[this.currentsize++] = e;
}
//向指定位置插入元素
public void add(int index,T e){
if (!this.checkcapacity()) {
this.spreadcapacity();
}
this.checkpos(index);
System.arraycopy(this.elem,index,this.elem,index+1,this.currentsize-index);
this.elem[index] = e;
this.currentsize++;
}
//查找
public int find(T e){
int i;
for(i = 0;i < this.currentsize;i++){
if(this.elem[i] == e){
return i+1;
}
}
return -1;
}
//返回指定下标的元素
public T findnum(int a){
this.checkpos(a);
return this.elem[a];
}
//删除(第一次出现的元素)
public void remove(T e){
if(this.find(e) == -1){
System.out.println("没有这个元素");
return;
}
int a =this.find(e);
for(a -= 1;a < currentsize - 1;a++){
this.elem[a] = this.elem[a + 1];
}
this.currentsize--;
}
//更新某个位置的值
public void update(int a,T e){
this.checkpos(a);
this.elem[a] = e;
}
//遍历输出顺序表
public void output() {
for (int i = 0; i < this.currentsize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
//清空顺序表
public void clear() {
/*for (int i = 0; i < this.usedSize; i++) {
this.elem[i] = null;//当顺序表内容是引用类型时要使用这种方法置空
}*/
this.currentsize = 0;
}
}
public class SeqList {
public static void main(String[] args) {
List<Integer> list = new List<>(5);
list.addlast(1);
list.add(1,2);
int a = list.find(2);
System.out.println(a);
list.remove(2);
list.add(0,8);
list.addlast(7);
System.out.println(list.findnum(2));
list.update(1,10);
list.output();
}
}
public class YiChang extends RuntimeException{
public YiChang(String message) {
super(message);
}
}