Search code examples
javagenericstype-conversiontype-parameter

Java Generics - Type mismatch in constructor


I'd have a question here considering java generics.

I have a generic class called LabyrinthImpl with type parameter T. Each instance has a 2D array T[][] values. The problem resides in the constructor, where I specify a file to be read into 2-dimensional char array.

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.

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? Any suggestions? Also, thanks in advance!


Solution

  • Your question doesn't make sense.
    If T isn't Character, what would you expect to happen?

    You should make a non-generic class that implements 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>.