【问题标题】:Merge two ArrayLists of Custom Object Type合并两个自定义对象类型的 ArrayList
【发布时间】:2015-03-25 09:27:40
【问题描述】:

我想将两个 ArrayList 合并为一个。这些 ArrayList 不是“字符串”的类型。对象类型是自定义类。

private ArrayList<NewsItem> newsList;
private ArrayList<NewsItem> eventList;
private ArrayList<NewsItem> combinedList;

这就是我尝试组合这两个 ArrayList 的方式:

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);;
        }
    }
}

应用程序正在崩溃。这种方法有什么问题?

【问题讨论】:

  • 您错过了列表中的新运算符:newsList = new ArrayList&lt;&gt;();
  • @Blackbelt 为什么我应该使用 newsList = new ArrayList();?对于私有 void combineArrays() 方法,newsList 和 evenList 不为空
  • 我只看到这些对象的声明,没有看到它们的初始化。你可以发布堆栈跟踪
  • @sajaz 如果您的现有列表不为空,则无关紧要。重要的是您要创建一个新列表来组合其他两个列表。必须先创建此 列表,然后才能使用它。因此,您在某处需要一个 new。 (除非您想将列表 B 附加到现有列表 A)

标签: java android arraylist


【解决方案1】:

你可以做的更简单...

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

如果您不想重复(意味着您已正确实现 equals()),那么您可以使用 HashSet,例如,但这意味着您不需要特定的元素顺序。

【讨论】:

    【解决方案2】:

    您可以使用 addAll() 方法:

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

    【讨论】:

      【解决方案3】:

      如果你想要一个新列表:

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

      为时已晚..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2018-11-14
        • 2018-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多