我正在尝试这样做:
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
}
}
}
实例化泛型已经够难的了,但更难的是T
这里没有默认的构造函数,它需要一个int
其构造函数中的参数。
如何才能做到这一点?
我问过一个跟进问题 https://stackoverflow.com/questions/2107034/java-classt-and-class-difference-when-used-from-within-outside-of-the-class这里也。如果您也能回答这个问题,我将不胜感激。
This question https://stackoverflow.com/questions/1090458/instantiating-a-generic-class-in-java是相关的,但仅在假设类具有默认构造函数的情况下才相关。
已经说过,您不能使用以下命令创建 T 的实例new
, 所以
我会使用工厂模式或原型模式
所以你的构造函数看起来像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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)