casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

后端 未结 7 1885
忘了有多久
忘了有多久 2020-11-29 08:17

I\'m new to Java and am trying to understand why the first code snippet doesn\'t cause this exception but the second one does. Since a string array is passed into Arrays.as

相关标签:
7条回答
  • 2020-11-29 08:42

    Using a debugger, I determined that Array.asList(titles) returns an "Arrays$ArrayList" (ie an inner class of the Arrays class) rather than a java.util.ArrayList.

    It's always best to use the interface on the left side of expressions, in this case List rather than the concrete ArrayList. This works fine:

        List<List<String>> stuff = new ArrayList<List<String>>();
        String[] titles = {"ticker", "grade", "score"};
        stuff.add((List<String>) Arrays.asList(titles));
    
    0 讨论(0)
提交回复
热议问题