如何正确地将 List 转换为我的对象类型的 ArrayList?
How do I properly convert List to ArrayList of my type of Object?
我有一个 JdbcTemplate
查询,它使用 queryForList
从数据库 table 中获取所有记录。我有一个主要在 ArrayList
上运行的 class,并且想将列表转换为 ArrayList<Customer>
。在调试器中,它可以很好地检索记录,但我无法弄清楚如何将 Object
转换为 Customer
并创建类型 Customer
的 ArrayList
。这是我的代码:
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 看来您需要 "hint" return 类型:
<T> List<T> queryForList(String sql, Class<T> elementType)
即打电话
List<Customer> customerList = jdbcTemplate.queryForList(query, Customer.class);
我有一个 JdbcTemplate
查询,它使用 queryForList
从数据库 table 中获取所有记录。我有一个主要在 ArrayList
上运行的 class,并且想将列表转换为 ArrayList<Customer>
。在调试器中,它可以很好地检索记录,但我无法弄清楚如何将 Object
转换为 Customer
并创建类型 Customer
的 ArrayList
。这是我的代码:
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 看来您需要 "hint" return 类型:
<T> List<T> queryForList(String sql, Class<T> elementType)
即打电话
List<Customer> customerList = jdbcTemplate.queryForList(query, Customer.class);