【问题标题】:How do I properly convert List to ArrayList of my type of Object?如何正确地将 List 转换为我的 Object 类型的 ArrayList?
【发布时间】:2016-02-19 22:24:14
【问题描述】:

我有一个JdbcTemplate 查询,它使用queryForList 从数据库表中获取所有记录。我有一个主要在ArrayLists 上运行的类,并且想将列表转换为ArrayList<Customer>。在调试器中,它可以很好地检索记录,但我无法弄清楚如何将Object 转换为Customer 并创建ArrayList 类型的Customer。这是我的代码:

public static ArrayList<Customer> getCustomers(){
        String query = "SELECT customerId,lastName,firstName,email,address,city,state,zip FROM " +
                "Customers";
        List customerList = jdbcTemplate.queryForList(query);
        ArrayList<Customer> customerArrayList = new ArrayList(customerList);
        return customerArrayList;
    }

【问题讨论】:

  • queryForList() 是什么样的?能否提供更多代码?
  • 您的 "在 ArrayLists 上运行的类" 是否有任何理由只能在 ArrayLists 上运行?为什么它不适用于任意类型的List&lt;&gt;?也就是说,与其尝试从queryForList 强制一个ArrayList,不如让你的其他类在任何列表实现上工作。

标签: java arraylist casting jdbctemplate


【解决方案1】:

List 裸露而不是List&lt;Customer&gt; 有什么原因吗?我相信这就是您需要解决的所有问题。

注意ArrayList支持构造函数

ArrayList(Collection<? extends E> c)

您正在尝试使用哪个。

Spring's JDBC Template documentation看来,您需要“提示”返回类型:

<T> List<T> queryForList(String sql, Class<T> elementType) 

即打电话

List<Customer> customerList = jdbcTemplate.queryForList(query, Customer.class);

【讨论】:

  • 如果我将 List 更改为 List 我会得到不兼容的类型
  • 谢谢,我会试一试的。我现在收到一个不同的错误,因为预期的列数不正确:1 实际 8。
  • 是的,我认为这可能无关紧要,但我认为您的解决方案是正确的。谢谢!
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
相关资源
最近更新 更多