Reputation: 4540
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?
Upvotes: 3
Views: 5679
Reputation: 96
If you want a new list :
ArrayList<NewsItem> combinedList = new ArrayList();
combinedList.addAll(newsList);
combinedList.addAll(eventList);
too late ..
Upvotes: 0
Reputation: 10652
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.
Upvotes: 4
Reputation: 1821
You can use addAll() method as:
combinedList.addAll(newsList);
combinedList.addAll(eventList);
Upvotes: 0