不能将 java.lang. ClassCastException: java.util.ArrayList $ArrayList 强制转换为 java.util.ArrayList

你能解释一下为什么会发生这种事吗? 我该怎么办?

所以我使用 Oracle-ADF 和穿梭组件

GetValue ()方法返回一个对象,我尝试将其转换为 ArrayList,以便稍后处理它。因此我创建了 ArrayList sos1Value

然而,这行代码变得越来越疯狂:

sos1Value = (ArrayList) Arrays.asList(sos1.getValue());

我一直收到 java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

我试过其他方法,比如: sos1Value = (ArrayList) sos1.getValue();

但我一直有同样的问题,我能做什么?

135757 次浏览

Arrays.asList(sos1.getValue()); produces an instance of a List implementation (java.util.Arrays$ArrayList) that is not java.util.ArrayList. Therefore you can't cast it to java.util.ArrayList.

If you change the type of sos1Value to List, you won't need this cast.

If you must have an instance of java.util.ArrayList, you can create it yourself :

sos1Value = new ArrayList (Arrays.asList(sos1.getValue()));

The ArrayList returned by Arrays.asList() method is NOT java.util.ArrayList it is a static inner class inside Arrays class. So, you can't cast it to java.util.ArrayList.

Try converting / assigning it to a List.

Arrays.asList returns a List implementation, but it's not a java.util.ArrayList. It happens to have a classname of ArrayList, but that's a nested class within Arrays - a completely different type from java.util.ArrayList.

If you need a java.util.ArrayList, you can just create a copy:

ArrayList<Foo> list = new ArrayList<>(Arrays.asList(sos1.getValue());

If you don't need an ArrayList just remove the cast:

List<Foo> list = Arrays.asList(sos1.getValue());

(if you don't need any members exposed just by ArrayList).

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

You need to set the type to java.util.List

The easy way (not efficient) is

ArrayList sos2Value = new ArrayList()
sos2Value.addAll(Arrays.asList(sos1.getValue()))

sos2Value is java.util.ArrayList.
Arrays.asList(sos1.getValue()) is java.util.Arrays$ArrayList

But I'm not clear what you want to do.

I used it in this way:

 private fun getArtists(): ArrayList<ArtistItem> {
var xp = myDb.daoNote().getArtists() as ArrayList<ArtistItem>
val x: List<ArtistItem> =  xp.sortedWith(compareBy { it.isBookmarked})
var pp = ArrayList<ArtistItem>()
for(obj in x)
{
pp.add(obj)
}


return pp
}