考虑到Java泛型,我在这里有一个问题。

我有一个名为LabyrinthImpl的泛型类,其类型参数为T。每个实例都有一个2D数组T[][] values。问题出在构造函数中,我在其中指定了一个文件
被读入二维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..

}


我想将T[][] values设置为char[][] vals,但是在这里发生类型不匹配。

所以我的问题是:有没有办法在这里告诉构造函数类型参数T应该解释为Character,以便它接受我的2d char数组?有什么建议?另外,预先感谢!

最佳答案

您的问题没有道理。
如果T不是Character,您期望发生什么?

您应该制作一个实现Labyrinth<Character>的非泛型类。

如果要在不读取文件时支持其他类型,则应使用返回Labyrinth<Character>的非泛型静态方法替换该构造函数。

10-07 19:26
查看更多