3

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?

4
  • you missed the new operator on your lists: newsList = new ArrayList<>(); Commented Mar 25, 2015 at 9:28
  • @Blackbelt Why should I use newsList = new ArrayList<>();? newsList and evenList are NOT empty when it comes to private void combineArrays() method Commented Mar 25, 2015 at 9:31
  • I see only the declaration of these objects, never their initialisation. Can you post the stacktrace Commented Mar 25, 2015 at 9:33
  • 1
    @sajaz It doesnt matter if your existing lists are not empty. What matters is that you want to create a new list to combine the other two lists. This new list must be created before you can use it. Therefore you need a new somewhere. (Unless you would want to append list B to existing list A) Commented Mar 25, 2015 at 9:35

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use addAll() method as:

combinedList.addAll(newsList);
combinedList.addAll(eventList);

Comments

0

If you want a new list :

 ArrayList<NewsItem> combinedList = new ArrayList();
 combinedList.addAll(newsList);
 combinedList.addAll(eventList);

too late ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.