在前端和后端交互的过程中,对于列表类的数据,有时候服务器发来的数据是重复的,这种列表类的数据大多和单元Bean类有联系,而且每个Bean一般都有id,所以,我们可以根据id来进行判断去重,然而怎么根据id来去重呢?这就需要我们重写Bean的equals和hashCode方法来比较了,上代码吧: 首先我们定义一个User的Bean类:
public class User extends Bean{ public String id; public String name; public int age; //去重关键,重写equals方法 @Override public boolean equals(Object o) { User user = (User) o; return user.id.equals(id); } //去重关键,把User的id当做对象的哈希表值返回 @Override public int hashCode() { return id.hashCode(); } }
测试代码:
import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import com.example.administrator.test.R;import com.example.administrator.test.bean.User;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;public class RemoveDepulicateDataActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_remove_depulicate_data); User user1 = new User(); user1.id = "12"; user1.name = "aaa"; user1.age = 10; User user2 = new User(); user2.id = "13"; user2.name = "aaa"; user2.age = 11; User user3 = new User(); user3.id = "14"; user3.name = "aaa"; user3.age = 11; User user4 = new User(); user4.id = "15"; user4.name = "aaa"; user4.age = 11; User user5 = new User(); user5.id = "15"; user5.name = "aaa"; user5.age = 11; Listlist = new ArrayList<>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); list.add(user5); remove(list); Log.e("after del depulicate",list.size()+""); } //去Bean类重 public void remove(List list){ Log.e("before del depulicate",list.size()+""); Set set = new HashSet<>(); List listaaa = new ArrayList<>(); for (Iterator ite = list.iterator();ite.hasNext();){ User aaa = ite.next(); if (set.add(aaa)){ listaaa.add(aaa); } } list.clear(); list.addAll(listaaa); }}
通过以上代码我们可以知道,HashSet的判重是根据元素的hashCode方法和equals方法共同决定的.送大家一片文章来温习下,hashCode和equals的原理.
新增
另一种的去重方式:```public void removeDepulicate(List list) { for ( int i = 0 ; i < list.size() - 1 ; i ++ ) { for ( int j = list.size() - 1 ; j > i; j -- ) { if (((DialogueBean) list.get(j)).getId().equals(((DialogueBean) list.get(i)).getId())) { list.remove(j); } } }}```