MMMMS
MMMMS

Reputation: 2201

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.

where am i doing wrong?

Upvotes: 0

Views: 71

Answers (2)

Crawler
Crawler

Reputation: 2018

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

Upvotes: 0

kai
kai

Reputation: 6887

You are using the add method of the List interface which only adds a single element to the list. Use the addAll method instead which will add another list.

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

Upvotes: 2

Related Questions