bgu*_*uiz 4 java generics instantiation default-constructor
我想这样做:
public class BaseTable<T extends TableEntry>
{
protected int mRows;
protected int mCols;
protected ArrayList<T> mEntries;
public BaseTable(int rows, int cols)
{
mRows = rows;
mCols = cols;
mEntries = new ArrayList<T>();
for (int i = 0; i < rows; i++)
{
mEntries.add(new T(cols)); //this obv. doesn't work
}
}
}
Run Code Online (Sandbox Code Playgroud)
实例化泛型很难实现,但更难以实现的是,T这里没有默认构造函数,它int在构造函数中需要一个参数.
如何才能做到这一点?
我也在这里问了一个跟进问题.如果你能回答这个问题,我将不胜感激.
这个问题是相关的,但只有在假定类具有默认构造函数时才有意义.
已经说过,你不能用T创建一个实例new,所以我会使用Factory Pattern或Prototype Pattern
所以你的构造函数看起来像是
public BaseTable(int rows, int cols, LineFactory factory)一个适当的工厂实例.
在你的情况下,我更喜欢原型模式,因为你的TableEntry对象可能非常轻量级.您的代码如下所示:
public BaseTable(int rows, int cols, T prototype)
{
mRows = rows;
mCols = cols;
prototype.setColumns(cols);
mEntries = new ArrayList<T>();
for (int i = 0; i < rows; i++)
{
@SuppressWarnings("unchecked")
T newClone = (T)prototype.clone();
mEntries.add(newClone); //this obv. does work :)
}
}
public static void main(String[] args)
{
new BaseTable<SimpleTableEntry>(10, 2, new SimpleTableEntry());
}
Run Code Online (Sandbox Code Playgroud)