当前位置: 移动技术网 > IT编程>开发语言>Java > list集合去除重复对象的实现

list集合去除重复对象的实现

2019年07月22日  | 移动技术网IT编程  | 我要评论

对象重复是指对象里面的变量的值都相等,并不定是地址。list集合存储的类型是基础类型还比较好办,直接把list集合转换成set集合就会自动去除。

当set集合存储的是对象类型时,需要在对象的实体类里面重写public boolean equals(object obj) {} 和 public int hashcode() {} 两个方法。

实体类

public class student {

public string id;
public string name;
public student() {
}
public student(string id,string name) {
this.id = id;
this.name = name;
}
public string getid() {
return id;
}
public void setid(string id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
@override
public boolean equals(object obj) {
student s=(student)obj; 
return id.equals(s.id) && name.equals(s.name); 
}
@override
public int hashcode() {
string in = id + name;
return in.hashcode();
}
}

测试类

import java.util.arraylist;
import java.util.hashset;
import java.util.list;
import java.util.set;

public class qusame {
 
 public static void main(string[] args) {
 list<student> stu = new arraylist<student>();
 stu.add(new student("1","yi"));
 stu.add(new student("3","san"));
 stu.add(new student("3","san"));
 stu.add(new student("2","er"));
 stu.add(new student("2","er"));
 //set集合保存的是引用不同地址的对象
 set<student> ts = new hashset<student>();
 ts.addall(stu);
 
 for (student student : ts) {
  system.out.println(student.getid()+"-"+student.getname());
 }
 }
}

以上这篇list集合去除重复对象的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网