【问题标题】:Get uncommon item from 2 arraylist从 2 arraylist 中获取不常见的项目
【发布时间】:2016-07-06 02:07:48
【问题描述】:

我想要的是从 2 个数组列表中获取不常见的项目

  • 我做了什么:

  • 代码:

      for (int i =0;i<arraylist1.size();i++)
            {                    
                idNew = arraylist.get(i).get("id");             
    
                if (idNew.equals(arraylist.get(i).get("id")))
                {
                    newAlert=true;                       
                }
                else {
                    newAlert=false;                       
                }
            }
    

-- 如果 newAlert 为 false ,则从 idNew

获取不常见的项目

【问题讨论】:

  • 帮助我们帮助您。您能否为arraylist 提供一些示例数据以及您试图获得的结果?
  • 哥们,昨天你也发了同样的问题,还是没解决?
  • @Mureinik,我需要身份证
  • @Amit Ranjan,你昨天回答了吗?
  • 点击这个链接你会得到答案 [link] (stackoverflow.com/questions/15575417/…)

标签: android arraylist


【解决方案1】:

你的检查方式是错误的,因为两个数组中的项可能不在同一顺序,所以你必须检查是否在另一个数组列表中没有找到所选择的项。

例如:arrayLists中的Class类型是Item

如果 idItem 对象中是唯一的,那么您可以实现 equals(Object o) >hashCode() 用于匹配对象

 @Override
 public boolean equals(Object o) {
    if(o instanceof Item){
        if(o.getId() == id){
            return true ;
        }
    }
    return false;
 }


 @Override
 public int hashCode() {
    return id*13;
 }

现在您可以匹配两个数组列表中的对象

 for (int i =0;i<arraylist1.size();i++)
    {                    
        Item itemObj = arraylist1.get(i);             

        if (arraylist.contains(itemObj))
        {
            newAlert=true;                       
        }
        else {
            newAlert=false;                       
        }
    }

如果您不想实现 equals(Object o)hashCode()您的解决方案可能如下

  for (int i =0;i<arraylist1.size();i++)
    {                    
        Item itemObj = arraylist1.get(i);   
        newAlert=false;            
        for (int index =0;index <arraylist.size();index++)
         { 
            Item item2 = arraylist.get(i); 
            if (item2.getId() == itemObj.getId())
            {
             newAlert=true;  
             break;                     
            }
         }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 2022-01-18
    • 2022-01-02
    • 2013-09-20
    • 2017-11-26
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多