0

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!

1
  • I'm just trying to learn using generics and wanted the constructor to support other types too, e.g. Integer. Seems like I need a while to get this stuff through my head. Commented Nov 14, 2011 at 12:10

1 Answer 1

4

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>.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for suggesting a non-generic static method. But even then, you can't assign a Character[][] to a char[][]; autoboxing only works for individual characters, not for arrays of characters.
Yeah, that might be clever. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.