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

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

    If you want to use your property as ArrayList<'T'> you need only declare there and create a getter.

        private static ArrayList bandsArrayList;
    
        public ArrayList getBandsArrayList() {
            if (bandsArrayList == null) {
                bandsArrayList = new ArrayList<>();
    
                String[] bands = {"Metallica", "Iron Maiden", "Nirvana"};
                bandsArrayList.addAll(Arrays.asList(bands));
            }
            return bandsArrayList;
        }
    

    Initializes the variable and use the method [addAll (Collection collection)](http://developer.android.com/intl/pt-br/reference/java/util/ArrayList.html#addAll(java.util.Collection))

提交回复
热议问题