2

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not doing exactly the same thing but your point is correct, is just an inheritance stuff.
1

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

Comments

1

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()) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.