Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have a class as this :

public class Questionnaire {

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

And I've initialized a new Questionnaire as 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 other 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 ?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer

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

share|improve this answer

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()) { ... }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.