BIG_MAC_AND_FRIES BIG_MAC_AND_FRIES - 2 months ago 5
Java Question

Dealing java.lang.ClassCastException: java.util.ArrayList cannot be cast to checkingAccount.BankEntry

Dealing with a ClassCastException, and haven't found an answer.

Am I supposed to parse elements using the ArraList, and then convert elements to StringsList?

I would appreciate some help in solving this issue.

This is my code that is causing the issue, but I don't know how to fix it:

I have these methods in the doGet method of my servlet.

public void init(ServletConfig config) throws ServletException {

super.init(config);


List<BankAccountEntry> entries = new ArrayList<BankAccountEntry>();

// Pre-populate the guestbook with a few entries
entries.add(new BankAccountEntry("efd", "df", 100.00, 24.40));

entries.add(new BankAccountEntry("dfd", "dfd", 45.00, 25.50));

entries.add(new BankAccountEntry("ssd", "dfd", 50.00, 65.50));


getServletContext().setAttribute("entries", entries);
}




List<BankAccountEntry> entries = (List<BankAccountEntry>) context.getAttribute("entries");






String query = request.getParameter("query");




This past causes the error, but not sure why:
if (query == null || ((BankAccountEntry) entries).getDescription().contains( query.trim() ) || ((BankAccountEntry) entries).getName().contains( query.trim() ) ) {
// Send the User back to the Guest Book page
}

String search = request.getParameter("query");

if (query == null || ((BankAccountEntry) entries).getDescription().contains( query.trim() ) || ((BankAccountEntry) entries).getName().contains( query.trim() ) ) {
// Send the User back to the Guest Book page
}

Answer

As per your code

List<BankAccountEntry> entries

entries is a List, but here

((BankAccountEntry) entries)

your are trying to cast it to a singular BankAccountEntry

Maybe in this code you should be iterating over the list?

if you want to iterate

for (BankAccountEntry bae : entries) {

   if (bae.getDescription().contains(query.trim()) {
      // whatever
   }
}
Comments