[英]Java Generics - Type mismatch in constructor
I'd have a question here considering java generics. 考虑到Java泛型,我在这里有一个问题。
I have a generic class called LabyrinthImpl with type parameter T
. 我有一个名为LabyrinthImpl的泛型类,其类型参数为T
Each instance has a 2D array T[][] values
. 每个实例都有一个二维数组T[][] values
。 The problem resides in the constructor, where I specify a file to be read into 2-dimensional char array. 问题出在构造函数中,在该构造函数中,我指定了要读取到二维char数组中的文件。
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..
}
I'd like to set T[][] values
to char[][] vals
but here a type mismatch occurs. 我想将T[][] values
为char[][] vals
但是这里发生类型不匹配。
So my question: is there a way to tell the constructor here the type parameter T should be interpreted as Character, so it would accept my 2d char array? 所以我的问题是:有没有办法在这里告诉构造函数类型参数T应该解释为Character,以便它接受我的2d char数组? Any suggestions? 有什么建议么? Also, thanks in advance! 另外,预先感谢!
Your question doesn't make sense. 您的问题没有道理。
If T
isn't Character
, what would you expect to happen? 如果T
不是Character
,您期望发生什么?
You should make a non-generic class that implements Labyrinth<Character>
. 您应该制作一个实现Labyrinth<Character>
的非泛型类。
If you want to support other types when not reading from files, you should replace that constructor with a non-generic static methods that returns a Labyrinth<Character>
. 如果要在不读取文件时支持其他类型,则应使用返回Labyrinth<Character>
的非泛型静态方法替换该构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.