This causes a java.lang.ClassCastException: [Ljava.lang.Object;

advertisements

I have a problem with the following code:

 List<book> list = new ArrayList();
    if(request.getAttribute("bookDeatils")!=null)
    {
        list = (ArrayList)request.getAttribute("bookDeatils");
            System.out.println("inside loop List --- "+list.size());
            for(book book : list)
                {
                out.println("<tr><td>"+book.getId()+"</td></tr>");
        }
          }
    System.out.printl``n(" List --- "+list.size());
%>

It is showing java.lang.ClassCastException: [Ljava.lang.Object;

What am I doing wrong?


Your List<book> is actually a List<Object[]>. This will cause a CCE in that enhanced for loop.

That can happen when you're doing something like SELECT b.id, b.title FROM Book b instead of SELECT b FROM Book b using JPA.


Unrelated to the concrete problem, your code style is very poor. Do not start Java classnames with lowercase. This is confusing to fellow developers and future maintainers. Learn Java Naming Coventions. Also do not write Java code in JSP files. Java code belongs in Java classes. You should use taglibs/EL only in JSP files. Learn Servlets and JSTL. Your whole loop can easily be done as follows then:

<c:forEach items="${bookDeatils}" var="bookDetail">
    <tr><td>${bookDetail.id}</td></tr>
</c:forEach>