Can you explain me why does this happen and how can I fix it please?
So I'm using Oracle-ADF and I'm using shuttle components. I get the selected values using the sos1.getValue();
The getValue() method returns an object and I'm trying to convert it to an ArrayList so I can work with it later. Therefore I've created the ArrayList sos1Value
However, this line of code is going bananas:
sos1Value = (ArrayList) Arrays.asList(sos1.getValue());
And I keep getting java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
I've tried other ways like: sos1Value = (ArrayList) sos1.getValue();
But I keep having the same problem, what can I do?
To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.
ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.
If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface. The program below shows the conversion of the list to ArrayList by adding all the list elements to the ArrayList.
The java. util. Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array.
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());
or:
List<Foo> list = new ArrayList<>(Arrays.asList(sos1.getValue()));
(if you don't need any members exposed just by ArrayList
).
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With