I'm trying to get a unmodifiable ArrayList to a final variable EX_FIELDS. exList is an existing ArrayList object.
EX_FIELDS = (ArrayList<String>) Collections.unmodifiableList(exList);
This code is present in a static block.When the class loads, I get the following error.
java.lang.ClassCastException: java.util.Collections$UnmodifiableRandomAccessList cannot be cast to java.util.ArrayList
I need to use the EX_FIELDS to support random access.Is there any other way to accomplish it?Thanks for any help in advance
EX_FIELDS
should have type List<String>
, not ArrayList<String>
, and you shouldn't need to do any cast: you should just write
EX_FIELDS = Collections.unmodifiableList(exList);
This is one instance of the much more general rule that you should program to the interface, not the implementation.
You get a ClassCastException because Collections.unmodifiableList()
doesn't return an ArrayList, it returns a List<T>
(interface) which can be any backing class that implements the List interface. As you can see from the exception, it is actually returning an UnmodifiableRandomAccessList
.
When you create the variable EX_FIELDS
you should declare it like
List<String> EX_FIELDS = new ArrayList<>();
That is, EX_FIELDS is a List and you have chosen an ArrayList for the actual instance. Later on you'll do
EX_FIELDS = Collections.unmodifiableList(exList);
unmodifiableList()
returns a List, but you don't care what kind it actually is, as long as it conforms to the List interface.
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