Question

I am trying to return an ArrayList of database search results from a servlet to be displayed on a jsp page.

Setting the arraylist as an attibute of request in the servlet and forwarding the request to the jsp page. when I try to retrieve it on the jsp page it it gives the following error:

"java.util.Vector cannot be cast to java.util.ArrayList"

The servlet code:

List<Car> ResultList=SearchPartsDAO.displaySearchResults(car);
        if(ResultList.size()>=1){
            request.setAttribute("ResultList", ResultList);
            request.getRequestDispatcher("SearchResults.jsp").forward(request, response);
        }else
            response.sendRedirect("NotFound.jsp");

The JSP:

<body>
<% 
ArrayList<Car> resultList = new ArrayList<Car>();
resultList=(ArrayList<Car>)request.getAttribute("ResultList");
%>
<%System.out.println(resultList.get(0).getCarMake());%>
Was it helpful?

Solution 2

The displaySearchResults() method is returning a Vector, which is a type of List, but is different from an ArrayList.

In your JSP you should declare resultList as List instead of ArrayList - then it doesn't matter which List implementation the DAO uses. Using the most generic type possible (i.e. List instead of Vector or ArrayList) for variable declarations, return types and parameters is a good practice to follow in general.

OTHER TIPS

You haven't shown your displaySearchResults method, but it sounds like that returns a Vector rather than an ArrayList. But fundamentally, you shouldn't care which implementation it returns - if you just cast to List<Car> instead, you should be fine:

<body>
<% 
List<Car> resultList = (List<Car>) request.getAttribute("ResultList");
%>
<%System.out.println(resultList.get(0).getCarMake());%>

Note how I've removed the initial assignment of an empty ArrayList - that's pointless if you're immediately going to assign a new value to the variable anyway.

It's cleaner to work in terms of the collection interfaces than the concrete classes - and you're already doing that in your first snippet of code. That only requires that the return value implements List<Car>, so you should only have the same requirement when you deal with the same value later.

It's also worth understanding that your cast to List<Car> is somewhat unsafe, in that it's only really casting to List, due to the lack of reified generics. You could still get a ClassCastException later when you access the individual elements, if they turn out to be some non-Car references. Unfortunately there's not a lot you can do about that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top