gpt4 book ai didi

java - 如何正确地将 List 转换为我的对象类型的 ArrayList?

转载 作者:行者123 更新时间:2023-11-30 08:04:33 25 4
gpt4 key购买 nike

我有一个 JdbcTemplate使用 queryForList 从数据库表中获取所有记录的查询.我有一个在 ArrayList 上运行的类主要是想将列表转换为 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;
}

最佳答案

有什么原因吗List是裸体而不是 List<Customer> ?我相信这就是您需要解决的全部问题。

备注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);

关于java - 如何正确地将 List 转换为我的对象类型的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com