Question What should i do to solve this ?
Answer: Find a tutorial about Collection framework in Java and read it.
If you want to store objects of different type in single list, you should create a list that can accept any object. Every object in Java inherit from Object
class. Therefore you need to create something like:
private List<Object> list4Everything = new ArrayList<>();
EDIT:
How ever if you have same object and you just want to merge two already existing list into new single one. You should use the method List#addAll(Collection c)
Lest do it on example, we will have three lists:
private List<YourType> list1 = new ArrayList<>();
private List<YourType> list2 = new ArrayList<>();
private List<YourType> mergeResult = new ArrayList<>();
You have various option to insert all data from list1
and 'list2' into mergeResult
Option 1 - Using addAll of megeResult.
mergeResult.addAll(list1);
mergeResult.addAll(list2);
Option 2 - Do it by hand.
for(YourType yt : list1) { //Itereate throug every item from list1
mergerResult.add(yt); //Add found item to mergerResult
}
for(YourType yt : list1) { //Itereate throug every item from list2
mergerResult.add(yt); //Add found item to mergerResult
}
Note: In this solution you have possibility to select witch item is added to meregeResult
.
So for example if we would like to have distinct result we could do something like this.
for(YourType yt : list1) { //Itereate throug every item from list1
if(mergerResult.contains(yt) == false) { //We check that item, already exits in mergeResult
mergerResult.add(yt); //Add found item to mergerResult
}
}
for(YourType yt : list1) { //Itereate throug every item from list2
if(mergerResult.contains(yt) == false) { //We check that item, already exits in mergeResult
mergerResult.add(yt); //Add found item to mergerResult
}
}
As we perform twice the same operation we could create a utilities class.
public static <T> boolean addAllNotContained(Collection<? super T> traget, Collection<? super T> source) {
//We should assure first that target or source are not null
int targetSize = target.size();
for(T item: source) {
if(target.contains(item) == false) {
target.add(item);
}
}
return targetSize != target.size();
}
Note: To have similar result of distinct merge you could use jest Set. It is created to not store duplicates.
The another option is too use already created framework that extend default Java one. The options are guava with iterables and apache commons