如何为两个对象使用Collections方法(removeAll()和retainAll())

zon*_*ono 0 java collections list apache-commons

我期望得到以下但实际上没有.即使它在我尝试使用String而不是Item Object时也能正常工作.我想知道为什么原因以及如何编码以获得预期的结果.谢谢.

EXPECTED
------------------------------
removed object are:
2
same object are:
1
3
add object are:
4
------------------------------
Run Code Online (Sandbox Code Playgroud)
ACTUAL
------------------------------
removed object are:
1
2
3
same object are:
add object are:
1
3
4
------------------------------
Run Code Online (Sandbox Code Playgroud)
package com.javastudy;

import java.util.ArrayList;
import java.util.List;

public class CollectionCompareToObjects {

 public static void main(String[] args) {

  List<Item> before = new ArrayList<Item>();
  List<Item> after = new ArrayList<Item>();

  before.add(new Item(1L));
  before.add(new Item(2L)); // delete
  before.add(new Item(3L));

  after.add(new Item(1L));
  after.add(new Item(3L));
  after.add(new Item(4L)); // added

  List<Item> removed = new ArrayList<Item>(before);
  removed.removeAll(after);

  System.out.println("removed objects are:");
  for(Item item : removed){
   System.out.println(item.getId());
  }

  List<Item> same = new ArrayList<Item>(before);
  same.retainAll(after);

  System.out.println("same objects are:");
  for(Item item : same){
   System.out.println(item.getId());
  }

  List<Item> added = new ArrayList<Item>(after);
  added.removeAll(before);

  System.out.println("add objects are:");
  for(Item item : added){
   System.out.println(item.getId());
  }

 }

}

package com.javastudy;

public class Item {

 Long id;

 public Item(Long id) {
  this.id = id;
 }

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

你没有实现equals()所以你的所有项目都是不同的对象,有些碰巧有一个相同的字段.

你需要实现equals.

我还建议你使用long而不是Long,除非你想要id = null.