0

What i want is getting uncommon items from 2 arraylist

  • what i have done :

  • code :

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

-- If newAlert is false , get uncommon item from idNew

tiger
  • 413
  • 1
  • 5
  • 18

1 Answers1

1

Your way of checking is wrong because the items in the two arrays may not be in the same order so you must check if the picked item not found in the other arraylist.

For Example : the Class type in the arrayLists is Item

If id is unique in Item object so you can implement equals(Object o) and hashCode() for objects matching

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

Now you can match objects in the two Array-lists

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

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

If you don't want to implement equals(Object o) and hashCode() your solution may be as following

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