当前位置: 移动技术网 > 移动技术>移动开发>Android > 去除arraylist容器中的相同的对象元素的方法

去除arraylist容器中的相同的对象元素的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论
<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方法后 。

如下:

	@override
	public boolean equals(object c){
		if (!(c instanceof employee)) {
			return false;
		}
		employee eoi = (employee) c;
		if (eoi.getuserguid().equals(userguid)) {
			return true;
		}
		return false;		
	}

上面的代码就可以正常运行了。

以上就是小编为大家带来的去除arraylist容器中的相同的对象元素的方法的全部内容了,希望对大家有所帮助,多多支持移动技术网~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网