I want to combine two ArrayList into a single one. These ArrayLists are NOT the type of "String". Object type is a custom class.
private ArrayList<NewsItem> newsList;
private ArrayList<NewsItem> eventList;
private ArrayList<NewsItem> combinedList;
This is how I am trying to combine those two ArrayLists:
private void combineArrays() {
if(newsList.size() > 0){
for (int i = 0; i<newsList.size(); i++){
NewsItem aBean = newsList.get(i);
combinedList.add(aBean);
}
}
if(eventList.size() > 0){
for (int i = 0; i<eventList.size(); i++){
NewsItem aBean = eventList.get(i);
combinedList.add(aBean);;
}
}
}
The app is crashing. What's the wrong with this approach?
You can do that simpler...
combinedList = new ArrayList<NewsItem>();
if (newsList != null)
combinedList.addAll( newsList );
if (eventList!= null)
combinedList.addAll( eventList);
If you don't want to have duplicates (implies you have implemented equals() correctly) then you could use a HashSet, for example, but that implies you don't need a specific order of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With