3

I'm trying to load data from file into JTable. So, using Java 8 streams it is very easy to load file into array of strings:

BufferedReader br = new BufferedReader(new FileReader(f));
Object[] data = br.lines().map((s)->{
            String[] res = {s,"1"}; // Here's some conversion of line into String[] - elements of one row
            return res;
        }).toArray();
TableModel m = new DefaultTableModel( (String[][])data, cols);

But the last line results in error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object. How can I cast data to String[][]?

2 Answers 2

8

If you use toArray(String[][]::new) instead of toArray() it will return a String[][] instead of an Object[] and you wont need to cast it at all (if you assign it to a String[][]).

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

Comments

-2

Splitting that piece of casting out into a loop should do it.

BufferedReader br = new BufferedReader(new FileReader(f));
Object[] data = br.lines().map((s)->{
        String[] res = {s,"1"}; // Here's some conversion of line into String[] - elements of one row
        return res;
    }).toArray();

String[][] dataMatrix = new String[data.length][];
for(int i = 0; i < data.length; i++){
    dataMatrix[i] = (String[]) data[i];
}
TableModel m = new DefaultTableModel(dataMatrix, cols);

Comments

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.