java - 如何使用 boja 类将一个列表添加到另一个列表

标签 java spring arraylist

我必须分别运行两个查询并添加到单个列表中,如下代码所示,

    List<BojaClass> results1 = new ArrayList<>();
    List<BojaClass> results2 = new ArrayList<>();
    String sql1 = "my query 1";
    String sql2 = "my query 2";
    results1 = jdbcTemplate.query(sql1, new Object[]{1,2}, new BeanPropertyRowMapper<BojaClass>(BojaClass.class));
    results2 = jdbcTemplate.query(sql2, new Object[]{1,2}, new BeanPropertyRowMapper<BojaClass>(BojaClass.class));
    results1.add((BojaClass) results2);

但我收到异常“java.lang.ClassCastException:java.util.ArrayList无法转换为com.myclass.BojaClass”,并且results2值未添加到results1中。

我哪里做错了?

最佳答案

您正在使用 List 接口(interface)的 add 方法,该方法仅将单个元素添加到列表中。使用 addAll 方法来添加另一个列表。

boolean java.util.List.add(E e)

Appends the specified element to the end of this list (optional operation).

boolean java.util.List.addAll(Collection c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

关于java - 如何使用 boja 类将一个列表添加到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333419/

相关文章:

java - CXF 以编程方式验证对象以进行测试

java - org.hibernate.TypeMismatchException : Provided id of the wrong type for class

java - 将 LinkedHashSet 转换为 ArrayList 或仅使用 ArrayList

java - 闹钟管理器或闹钟

java - 如何用空格左填充整数?

java - 如何使用 Hibernate 读取加密的数据库字段

java - 在基于maven配置文件的spring-boot项目中跳过maven shade插件

java - DTO、DAO 和 DCO。什么是 DCO?

java - 从 ArrayList 中删除对象而不(隐式)循环遍历它

java - 如何判断数组列表上的 for 循环是否已结束?