Java 8. Casting Object[] to String[][]

Deadly 提交于 2019-12-20 02:27:42

问题


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[][]?


回答1:


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[][]).




回答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);


来源:https://stackoverflow.com/questions/25234881/java-8-casting-object-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!