Bax
Bax

Reputation: 4476

What's the exact cause of the class cast exception in the next code?

public class Main {
    public static void main(String[] args) {
        List<Object[]> list = getIt();

//        unsuccessful iteration, throws ClassCastException
        for (Object id : list) {
            System.out.println(id);
        }

//        successful iteration  
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    private static List<Object[]> getIt() {
        List list = new ArrayList();
        list.add(1L);
        return list;
    }
}

I understand at a rough estimate what happens(the iterator generated by the compiler contains an explicit cast), but would like some good answers, thanks.

Upvotes: 0

Views: 366

Answers (2)

Bax
Bax

Reputation: 4476

Well, I think it's because under the cover the java compiler generates smth like this :

Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println((Object[])iterator.next());
        }

and the explicit cast gives the error. Generally, it's the problem of mixing generics with raw types, but, as I already said, I don't speak here about best practices.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

When I run this with Java 7 I don't get a ClassCastException, nor would I expect it to as the object is cast as Object in main();

Upvotes: 1

Related Questions