去除arraylist容器中的相同的对象元素的方法
<spanclass="keyword"style="background-color:rgb(250,250,250);font-size:1em;font-family:Monaco,'DejaVuSansMono','BitstreamVeraSansMono',Consolas,'CourierNew',monospace;">boolean</span><spanstyle="color:black;background-color:rgb(250,250,250);font-size:1em;font-family:Monaco,'DejaVuSansMono','BitstreamVeraSansMono',Consolas,'CourierNew',monospace;"> retainAll(Collection<?> c); </span>
在网上查到了retainAll方法
然后就在代码中添加
<prename="code"class="html">List<Employee><spanstyle="font-family:Arial,Helvetica,sans-serif;">employeeOfIntermediarys</span><spanstyle="font-family:Arial,Helvetica,sans-serif;">=newArrayList<Employee>(); </span><prename="code"class="html">List<Employee><spanstyle="font-family:Arial,Helvetica,sans-serif;">tempList</span><spanstyle="font-family:Arial,Helvetica,sans-serif;">=newArrayList<Employee>();</span>
if(tempList!=null){ <spanstyle="white-space:pre"> </span>//去掉<spanstyle="font-family:Arial,Helvetica,sans-serif;">tempList中与</span><spanstyle="font-family:Arial,Helvetica,sans-serif;">employeeOfIntermediarys中</span>相同的元素,在合并 List<Employee>eoiList=newArrayList<Employee>(employeeOfIntermediarys); if(eoiList.retainAll(tempList)){ tempList.removeAll(eoiList); }
employeeOfIntermediarys.addAll(tempList); }
然后发现不可以,查了好多东西,发现代码是对的,只是需要重写equals方法。
不知道为什么,因为之前写的小demo中用自定义的类book,如下,是可以正常使用的
publicclassBook{ privateintid; privateStringnameString; privateStringwriter; publicBook(){ id=-1; nameString=""; writer=""; }
List<Book>books=newArrayList<Book>(); List<Book>tempList=newArrayList<Book>(); Bookbook1=newBook(); book1.setId(1); book1.setNameString("dkjdf"); Bookbook2=newBook(); book2.setId(2); book2.setNameString("到加福禄寿"); Bookbook3=newBook(); book3.setId(3); book3.setNameString("dj地方"); Bookbook4=newBook(); book4.setId(4); book4.setNameString("dkjdf"); Bookbook5=newBook(); book5.setId(5); book5.setNameString("到加福禄寿"); Bookbook6=newBook(); 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方法后。
如下:
@Override publicbooleanequals(Objectc){ if(!(cinstanceofEmployee)){ returnfalse; } Employeeeoi=(Employee)c; if(eoi.getUserGuid().equals(userGuid)){ returntrue; } returnfalse; }
上面的代码就可以正常运行了。
以上就是小编为大家带来的去除arraylist容器中的相同的对象元素的方法的全部内容了,希望对大家有所帮助,多多支持毛票票~