【问题标题】:Java Generics - Type mismatch in constructorJava 泛型 - 构造函数中的类型不匹配
【发布时间】:2011-12-28 07:48:12
【问题描述】:

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

我有一个名为 LabyrinthImpl 的泛型类,其类型参数为 T。每个实例都有一个二维数组T[][] values。问题出在构造函数中,我在其中指定了一个文件 读入二维字符数组。

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 应该被解释为字符,所以它会接受我的 2d char 数组?有什么建议?另外,提前谢谢!

【问题讨论】:

  • 我只是想学习使用泛型并希望构造函数也支持其他类型,例如整数。看来我需要一段时间才能理解这些东西。

标签: java generics type-conversion type-parameter


【解决方案1】:

你的问题没有意义。
如果T 不是Character,你希望发生什么?

您应该创建一个实现Labyrinth&lt;Character&gt; 的非泛型类。

如果您想在不从文件读取时支持其他类型,则应将该构造函数替换为返回 Labyrinth&lt;Character&gt; 的非泛型静态方法。

【讨论】:

  • +1 用于建议非泛型静态方法。但即便如此,您也不能将Character[][] 分配给char[][];自动装箱仅适用于单个字符,不适用于字符数组。
  • 是的,这可能很聪明。谢谢。
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多