Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two ArrayLists of Custom Object Type

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?

like image 762
smartsanja Avatar asked Jan 24 '26 00:01

smartsanja


1 Answers

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.

like image 188
Florian Schaetz Avatar answered Jan 26 '26 14:01

Florian Schaetz