Java 泛型 - 构造函数中的类型不匹配

标签 java generics type-conversion type-parameter

我在这里有一个关于 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/

相关文章:

java - Lotus Notes Java 代理的 GSON 库错误 - java.lang.NoClassDefFoundError : com. google.gson.JsonObject

java - 修改其他类中声明的对象的最佳方法(Java)

c++ - Qt QString::toDouble() 返回 int 0

android - 使用 RealmMigration 在 Realm Android 中将数据类型从 String 更改为 Long

javascript - Double not (!!) 与 JavaScript 中的类型强制

java :Why the Local variable should be declared final

java - dom4j 在读取时忽略 xmlns 属性

java - 在方法中使用@SuppressWarnings 会产生编译错误

c# - 转换为 Tuple<object,object>

generics - Dart 2.7通用扩展