Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

Error: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

I have a class like this:

public class Questionnaire {

    private String         questionnaireLibelle;
    private List<Question> questions;
    // ...

}

And I've initialized a new Questionnaire like this:

Questionnaire q = new Questionnaire(
                "Architecture des ordinateurs",
                Arrays.asList(
                    new Question( "1. La partie du processeur spécialisée pour les calculs est :"),
                    new Question("2. Dans un ordinateur, les données sont présentées par un signal électrique de la forme :"),
                    new Question("3. Les différents éléments d’un ordinateur (mémoire, processeur, périphériques…) sont reliés entre eux par des:")
                )
        );

As you see I used Arrays.asList() instead of declaring a new ArrayList.

In another class I used this code:

for(Question q : (ArrayList<Question>) request.getAttribute("listQuestions"))

But I got this error for that line:

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

How can I solve this?

Upvotes: 2

Views: 8333

Answers (3)

SebastianH
SebastianH

Reputation: 2182

The return type of the Arrays.asList(...) function is a List<T>. Therefore you must not make any assumptions about the concrete type of the class used to implement the List interface.

Internally any kind of list could be used by Arrays.asList. Of course one might expect that an ArrayList is used here, but this could be changed with every Java version.

I guess what you want is closer to this (I simplified a bit):

public class Questionnaire {

    private String         questionnaireLibelle;
    private List<Question> questions;

    public List<Question> getQuestions() { return questions; }
.....
}

And then:

for(Question q : request.getQuestions()) { ... }

Upvotes: 1

Welington Veiga
Welington Veiga

Reputation: 151

You dont need to cast, just iterate over request.getAttribute("listQuestions"), the List implementation returned by Arrays.asList, and all Collections instances, are implementations of 'Iterable' and you can use then in for(... in ...).

More: http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html

Upvotes: 1

Jorge_B
Jorge_B

Reputation: 9872

This happened because you used the concrete type in your cast. Try just this:

for(Question q : (List<Question>) request.getAttribute("listQuestions"))

Since you have the guarantee that it uses the interface. As a style guide, always prefer the use of the interface to concrete types.

Upvotes: 3

Related Questions