简体   繁体   English

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

[英]how to add one list to another list with boja class

I have to run two query separately and add in single list like below code, 我必须分别运行两个查询,并像下面的代码一样添加一个列表,

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

But i am getting exception " java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.myclass.BojaClass " and results2 values not adding to results1. 但是我收到异常“ java.lang.ClassCastException:java.util.ArrayList无法转换为com.myclass.BojaClass ”,并且results2值未添加到results1中。

where am i doing wrong? 我在哪里做错了?

You are using the add method of the List interface which only adds a single element to the list. 您正在使用List接口的add方法,该方法仅将单个元素添加到列表中。 Use the addAll method instead which will add another list. 改用addAll方法将添加另一个列表。

boolean java.util.List.add(E e) 布尔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) 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.) (请注意,如果指定的集合是此列表,并且是非空的,则将发生这种情况。)

There is error in your casting: 您的转换中有错误:

results1.add((BojaClass) results2);

Above should be changed to: 以上应更改为:

results1.add((List<BojaClass>) results2);

Hope this fix your issue 希望这能解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM