Java 如何正确地将对象类型的列表转换为ArrayList?
我有一个Java 如何正确地将对象类型的列表转换为ArrayList?,java,arraylist,casting,jdbctemplate,Java,Arraylist,Casting,Jdbctemplate,我有一个JdbcTemplate查询,它使用queryForList从数据库表中获取所有记录。我有一个类主要在ArrayLists上运行,并且希望将列表转换为ArrayList。在调试器中,它可以很好地检索记录,但我很难弄清楚如何将对象强制转换为客户,并创建客户类型的数组列表。这是我的密码: public static ArrayList<Customer> getCustomers(){ String query = "SELECT customerId,lastN
JdbcTemplate
查询,它使用queryForList
从数据库表中获取所有记录。我有一个类主要在ArrayList
s上运行,并且希望将列表转换为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;
}
publicstaticarraylistgetcustomers(){
String query=“选择customerId、姓氏、姓氏、电子邮件、地址、城市、州、邮政编码来源”+
“客户”;
List customerList=jdbcTemplate.queryForList(查询);
ArrayList customerArrayList=新的ArrayList(customerList);
返回customerArrayList;
}
是否有任何原因导致列表
是裸体的而不是列表
?我相信这就是你需要解决的所有问题
注意ArrayList
支持构造函数
ArrayList(Collection<? extends E> c)
ArrayList(collectionqueryForList()
看起来像什么?你能提供更多的代码吗?你的“在ArrayLists上操作的类”有什么原因吗必须只在ArrayList上运行?为什么它不能在任意类型的列表上运行呢?也就是说,与其试图从queryForList
强制运行ArrayList,不如让您的其他类在任何列表实现上运行。如果我将List更改为List,我会得到不兼容的类型Hanks,我会尝试一下。我得到了一个不同的错误对于不正确的列计数,现在应为:1实际值8。是的,我认为这可能是无关的,但我认为您的解决方案是正确的。谢谢!
<T> List<T> queryForList(String sql, Class<T> elementType)
List<Customer> customerList = jdbcTemplate.queryForList(query, Customer.class);