在Java中思考時,第566頁給出以下示例。關於說明通用類語法的用法的示例
class CountedInteger {
private static long counter;
private final long id = counter++;
public String toString() { return Long.toString(id); }
}
public class FilledList<T> {
private Class<T> type;
public FilledList(Class<T> type) { this.type = type; }
public List<T> create(int nElements) {
List<T> result = new ArrayList<T>();
try {
for(int i = 0; i < nElements; i++)
result.add(type.newInstance());
} catch(Exception e) {
throw new RuntimeException(e);
}
return result;
}
public static void main(String[] args) {
FilledList<CountedInteger> fl = new FilledList<CountedInteger>(CountedInteger.class);
System.out.println(fl.create(15));
}
}
我對這個例子有三個問題。
1)什麼是私人類類型的用法?爲什麼是私人的?
2)爲什麼下面,特別是「this.type = type;」
public FilledList(Class<T> type) { this.type = type; }
3)作者聲稱:
注意,這個類必須假設它的工作原理與 任何類型都有一個默認的構造函數(不帶參數),你會得到一個 如果情況並非如此,則例外。
我無法弄清楚這個聲明是如何反映在上面的例子中的。謝謝。