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

后端 未结 7 2093
忘了有多久
忘了有多久 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:23

    The problem is you specified your List to contain ArrayLists - and by implication no other List implementations. Arrays.asList() returns its own implementation of a List based on the implementation of the array parameter, which may not be an ArrayList. That's your problem.

    More broadly, you have a classic code style problem: You should be referring to abstract interfaces (ie List), not concrete implementations (ie ArrayList). Here's how your code should look:

    List> stuff = new ArrayList>();
    String[] titles = { "ticker", "grade", "score" };
    stuff.add((List) Arrays.asList(titles));
    

    I have tested this code, and it runs without error.

提交回复
热议问题