我在这里有一个关于 java 泛型的问题。
我有一个名为 LabyrinthImpl 的泛型类,其类型参数为 T
。每个实例都有一个二维数组T[][]值
。问题出在构造函数中,我在其中指定了一个文件
读入二维字符数组。
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[][] 值
设置为 char[][] vals
,但这里发生类型不匹配。
所以我的问题:有没有办法告诉构造函数这里类型参数 T 应该被解释为字符,所以它会接受我的二维字符数组?有什么建议么?另外,提前致谢!
最佳答案
你的问题没有意义。
如果T
不是Character
,您希望发生什么?
您应该创建一个实现 Labyrinth<Character>
的非泛型类.
如果您想在不从文件读取时支持其他类型,则应将该构造函数替换为返回 Labyrinth<Character>
的非泛型静态方法。 .
关于Java 泛型 - 构造函数中的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8116487/