//所有類別都是Object的子類別,所以在new時都可以先歸類在Object中
//因此可以製造出一個包容萬物的陣列,之後取出時再轉回子類別
Object[] objs = {"Tim",new Date()};
String name = (String) objs[0];
Date date = (Date) objs[1];
package tw.tinachang.myfirstproject.game;
import java.util.Arrays;
import java.util.Scanner;
class ArrayList{//覆寫
private Object[] elems;//創造一個一維private陣列,限定收取Object的物件(等於所有物件),取名elems
private int next;//此為下一個可儲存物件的索引,初始值為預設的0
public ArrayList(int capacity){//有一個參數的建構子
this.elems = new Object[capacity];
//一旦new一個新的一個參數的ArrayList物件時,則會直接產生一個名叫elems,長度為capacity的陣列,內中可以放入Object型別的物件
}
public ArrayList(){//沒有參數的建構子
this(16);
//上面這行等於 this.elems = new Object[16];
//也就是不指定長度時,產生預設長度為16的陣列
}
public void add(Object o){//建立一個方法可以把新增的東西放到陣列裡
if(next==elems.length){//如果下一個可以儲存的物件索引就是長度,等於是最後一個了
elems = Arrays.copyOf(elems, elems.length*2);//複製一個新陣列,並把那就把長度加倍,然後放回原來的變數裡(貼上原來的標籤),所以就像他加長了一樣
//API對此方法的描述:Copies the specified array, truncating or padding with
//zeros (if necessary) so the copy has the specified length.
//複製的新東西應該是可以變短也可以變長的,例如elems.length/2
}
elems[next++] = o;//把東西(o)放入陣列裡
}
public Object get(int index){//取物
return elems[index];
}
public int size(){//目前陣列有擺放物品的大小
return next;
}
}
public class GamePolymorphismDetial {
static void collectNameTo(ArrayList names){//創造一個方法,必須放入ArrayList類別的物件
Scanner console = new Scanner(System.in);//System.in是一個可以讓使用者輸入的語法,new成Scanner則可以暫存於變數console中
//但是System.in輸入進來的資料型態是static InputStream
//API:Scanner(InputStream source)
//Constructs a new Scanner that produces values scanned from the specified input stream.
while(true){//無限迴圈
System.out.print("訪客名稱:");
String name = console.nextLine();
//next.Line()是Scanner底下的一個方法,用來把輸入到console中的資料一行行取出使用
//This method returns the rest of the current line, excluding any line separator at the end.
//The position is set to the beginning of the next line.
if( name.equals("Q")){
break;//輸入Q時結束無線迴圈
}
names.add(name);//把輸入的名字放入陣列names中
}
}
public static void main(String[] args) {
ArrayList names = new ArrayList();
collectNameTo(names);//static void collectNameTo 可以直接使用,不用加上類別名稱
System.out.println("訪客名單為:");
for (int i=0;i<names.size();i++){//把剛剛輸入的結果印出來
String name = (String)names.get(i);//使用ArrayList內自訂語法get
System.out.println(name);
}
}
}
輸入內容:
訪客名稱:李大同
訪客名稱:王小花
訪客名稱:陳中明
訪客名稱:Q
傳出結果:
訪客名單為:
李大同
王小花
陳中明