处理java.lang.ClassCastException:java.util.ArrayList无法强制转换为checkingAccount.BankEntry

时间:2016-10-04 06:37:11

标签: java

处理ClassCastException,但未找到答案。

我是应该使用ArraList解析元素,然后将元素转换为StringsList?

我很感激帮助解决这个问题。

这是导致问题的我的代码,但我不知道如何修复它:

我在servlet的doGet方法中有这些方法。

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
        }   

1 个答案:

答案 0 :(得分:2)

根据您的代码

List<BankAccountEntry> entries

条目是一个列表,但这里

((BankAccountEntry) entries)

您正试图将其转换为单数BankAccountEntry

也许在这段代码中你应该遍历列表?

如果你想迭代

for (BankAccountEntry bae : entries) {

   if (bae.getDescription().contains(query.trim()) {
      // whatever
   }
}
相关问题