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

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

    If you do this, you won't get any CCE:

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

    As the error clearly states, the class java.util.ArrayList isn't the same as nested static class java.util.Arrays.ArrayList. Hence the exception. We overcome this by wrapping the returned list using a java.util.ArrayList.

提交回复
热议问题