【发布时间】:2011-12-28 07:48:12
【问题描述】:
考虑到 java 泛型,我在这里有一个问题。
我有一个名为 LabyrinthImpl 的泛型类,其类型参数为 T。每个实例都有一个二维数组T[][] values。问题出在构造函数中,我在其中指定了一个文件
读入二维字符数组。
public class LabyrinthImpl<T> implements Labyrinth<T> {
/**
* 2d array to hold information about the labyrinth.
*/
private T[][] values;
/**
* Constructor.
* @param values 2d array to hold information about the labyrinth.
*/
public LabyrinthImpl(T[][] values) {
this.values = values;
}
/**
* Constructor.
* @param file File from which to read the labyrinth.
* @throws IOException
*/
public LabyrinthImpl(File file) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(file));
LinkedList<String> list = new LinkedList<String>();
String line;
int maxWidth = 0;
while((line = in.readLine()) != null)
{
list.add(line);
if(line.length() > maxWidth)
maxWidth = line.length();
}
char[][] vals = new char[list.size()][maxWidth];
for(int i = 0; i < vals.length; i++)
{
vals[i] = list.remove().toCharArray();
}
values = vals; //not working, type mismatch
}
//methods..
}
我想将T[][] values 设置为char[][] vals,但这里会出现类型不匹配。
所以我的问题是:有没有办法在这里告诉构造函数类型参数 T 应该被解释为字符,所以它会接受我的 2d char 数组?有什么建议?另外,提前谢谢!
【问题讨论】:
-
我只是想学习使用泛型并希望构造函数也支持其他类型,例如整数。看来我需要一段时间才能理解这些东西。
标签: java generics type-conversion type-parameter