TestMain.java
package listTest;
public class TestMain {
public static void main(String[] args){
MyList<String> myList = new MyList<>();
myList.add("1");
myList.add("2");
myList.add("3");
// myList.add("4");
// myList.add("3");
// myList.add("3");
// myList.add("3");
// myList.add("3");
// myList.add("3");
// myList.add("3");
// myList.add("3");
for(int i = 0 ; i < myList.getIndex() ; i++){
System.out.println(myList.get(i));
}
// System.out.println(myList.getSize());
// System.out.println(myList.isEmpty());
// System.out.println("刪除成功");
// myList.clear();
// for(int i = 0 ; i < myList.getIndex() ; i++){
// System.out.println(myList.get(i));
// }
myList.remove(1);
for(int i = 0 ; i < myList.getIndex() ; i++){
System.out.println(myList.get(i));
}
}
}
MyList.java
package listTest;
public class MyList<E> {
//将List的長度初始化爲10
private E[] eList = (E[]) new Object[10];
private int index = 0;
public boolean add(E e){
if(index < eList.length){
//把el添加到List當中
eList[index] = e ;
index ++ ;
}//如果List滿了則擴充長度
else{
E[] tList = (E[]) new Object[eList.length * 2];
//將eList賦給tList
System.arraycopy(eList, 0, tList, 0, eList.length);
//將eList指向tList
eList = tList ;
eList[index] = e ;
index ++ ;
System.out.println("擴充了!");
}
System.out.println("添加成功!");
return true;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
/*
* get
*/
public Object get(int index){
return eList[index];
}
/*
* size
*/
public int getSize(){
return index;
}
/*
* isEmpty
*/
public boolean isEmpty(){
if(index == 0 ){
return true;
}else{
return false;
}
}
/*
* clear
*/
public void clear(){
for(int i = 0 ; i < index ; i++){
eList[i] = null;
}
index = 10;
}
/*
* remove
*/
public Object remove(int i){
eList[i] = null;
for( ; i < index; i ++){
eList[i] = eList[++i];
}
index --;
return eList;
}
}
java_自定義一個List(類似ArrayList),布布扣,bubuko.com