[問題] Constructor問題

作者: stenler (挖哈哈思壓)   2015-05-30 16:23:15
如題, 我建立了一個如下的代碼, 本來認為 CCC 應該要輸出5次, 結果卻只有一次 ..
如果我想要讓陣列理的元素也去call constructor, 該怎麼作呢?
public class test {
public test(){
System.out.println("CCC");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
test ddd = new test();
test[] ccc = new test[4];
}
}
作者: Frozenmouse (*冰之鼠*)   2015-05-30 16:27:00
你第二句new的不是test,是test[] XD把陣列裡的元素指去新的物件就行了
作者: stenler (挖哈哈思壓)   2015-05-30 16:47:00
F大是說用一個for迴圈搞定嗎?
作者: ssccg (23)   2015-05-30 18:35:00
ccc = new test[4]後,ccc裡面是4個null,沒有陣列裡的元素
作者: Frozenmouse (*冰之鼠*)   2015-05-30 18:55:00
詳情就是樓上說的那樣,然後用迴圈當然可以
作者: Killercat (殺人貓™)   2015-05-30 20:35:00
我覺得你把new test[4]換成new ArrayList<test>(4)這樣看你應該就不會搞混了....你會覺得ArrayList<test> ccc= new ArrayList<>(4);會幫你跑四次test constructor嗎? XD

Links booklink

Contact Us: admin [ a t ] ucptt.com