Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an ArrayList to an unmodifiable ArrayList

Tags:

java

arraylist

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

like image 459
amudhan3093 Avatar asked Dec 04 '22 22:12

amudhan3093


2 Answers

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.

like image 124
Louis Wasserman Avatar answered Dec 06 '22 11:12

Louis Wasserman


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.

like image 20
Stephen P Avatar answered Dec 06 '22 13:12

Stephen P