去除ArrayList容器中的相同的对象元素

来源:互联网 发布:js比较日期差值 编辑:程序博客网 时间:2024/04/29 06:45
  1. <span class="keyword" style="background-color: rgb(250, 250, 250); font-size: 1em; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace;">boolean</span><span style="color: black; background-color: rgb(250, 250, 250); font-size: 1em; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Consolas, 'Courier New', monospace;"> retainAll(Collection<?> c); </span>

在网上查到了 retainAll方法

然后就在代码中添加

<pre name="code" class="html">List<Employee> <span style="font-family: Arial, Helvetica, sans-serif;">employeeOfIntermediarys </span><span style="font-family: Arial, Helvetica, sans-serif;">= new ArrayList<Employee>();</span><pre name="code" class="html">List<Employee> <span style="font-family: Arial, Helvetica, sans-serif;">tempList </span><span style="font-family: Arial, Helvetica, sans-serif;">= new ArrayList<Employee>();</span>

///////
///
//
if(tempList != null){<span style="white-space:pre"></span>//去掉<span style="font-family: Arial, Helvetica, sans-serif;">tempList 中与</span><span style="font-family: Arial, Helvetica, sans-serif;">employeeOfIntermediarys 中</span>相同的元素,在合并List<Employee> eoiList = new ArrayList<Employee>(employeeOfIntermediarys);if (eoiList.retainAll(tempList)) {tempList.removeAll(eoiList);}
employeeOfIntermediarys.addAll(tempList);}
然后发现不可以,查了好多东西,发现代码是对的,只是需要重写equals方法。

不知道为什么,因为之前写的小demo中用自定义的类book,如下,是可以正常使用的

public class Book {private int id;private String nameString;private String writer;public Book(){id= -1;nameString = "";writer = "";}
/////////////////////////略

List<Book> books = new ArrayList<Book>();   List<Book> tempList = new ArrayList<Book>();      Book book1 = new Book();   book1.setId(1);   book1.setNameString("dkjdf");      Book book2 = new Book();   book2.setId(2);   book2.setNameString("到加福禄寿");      Book book3 = new Book();   book3.setId(3);   book3.setNameString("dj地方");      Book book4 = new Book();   book4.setId(4);   book4.setNameString("dkjdf");      Book book5 = new Book();   book5.setId(5);   book5.setNameString("到加福禄寿");      Book book6 = new Book();   book6.setId(6);   book6.setNameString("dj地方");         books.add(book1);   books.add(book2);   books.add(book5);   books.add(null);      tempList.add(book1);   tempList.add(book4);   tempList.add(null);   tempList.retainAll(books);   System.out.println(tempList.get(0).booktoString());
 

whatever,准备找一找collection的源代码看看,

重写了Employee中的equals方法后 。如下:

@Overridepublic boolean equals(Object c){if (!(c instanceof Employee)) {return false;}Employee eoi = (Employee) c;if (eoi.getUserGuid().equals(userGuid)) {return true;}return false;}
上面的代码就可以正常运行了。





0 0