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

后端 未结 7 2063
忘了有多久
忘了有多久 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条回答
  •  萌比男神i
    2020-11-29 08:39

    First, Arrays.asList() should be never casted to ArrayList. Second, since generics were introduced into java programming language casting is still relevant when using legacy, pre-generics APIs.

    Third, never use concrete classes at the left of assignment operator.

    Bottom line, say

    List> stuff = new ArrayList>();
    String line = "a,b,cdef,g";
    String delim = ",";
    String[] pieces = line.split(delim);
    stuff.add(Arrays.asList(pieces));
    
    
    
    List> stuff = new ArrayList>();
    String[] titles = {"ticker", "grade", "score"};
    stuff.add(Arrays.asList(titles));
    

    and be happy.

提交回复
热议问题