繁体   English   中英

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

[英]Java Generics - Type mismatch in constructor

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

我有一个名为LabyrinthImpl的泛型类,其类型参数为T 每个实例都有一个二维数组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[][] valueschar[][] vals但是这里发生类型不匹配。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM