Java List实体类去重
今天写了一段代码判断list中是否包含某个实体openSubjectDTO,不包含就添加进去,发现不好使
if(!subjectList.contains(openSubjectDTO)){
subjectList.add(openSubjectDTO);
}
后来发现是openSubjectDTO类中缺少两个方法如下:
List 去除重复Object对象:
对象重复是指对象里面的变量的值都相等,并不定是地址。list集合存储的类型是基础类型还比较好办,直接把list集合转换成set集合就会自动去除。
当set集合存储的是对象类型时,需要在对象的实体类里面重写public boolean equals(Object obj) {} 和 public int hashCode() {} 两个方法。
List特点:元素有放入顺序,元素可重复
Map特点:元素按键值对存储,无放入顺序
Set特点:元素无放入顺序,元素不可重复(注意:元素虽然无放入顺序,但是元素在set中的位置是有该元素的HashCode决定的,其位置其实是固定的)
新建一个实体类
- public class User {
- private String id;
- private String name;
- private String age;
- private String address;
- 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;
- }
- public String getAge() {
- return age;
- }
- public void setAge(String age) {
- this.age = age;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((age == null) ? 0 : age.hashCode());
- result = prime * result + ((address == null) ? 0 : address.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- User other = (User) obj;
- if (id == null) {
- if (other.id != null) {
- return false;
- }
- } else if (!id.equals(other.id)) {
- return false;
- }
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (age == null) {
- if (other.age != null) {
- return false;
- }
- } else if (!age.equals(other.age)) {
- return false;
- }
- if (address == null) {
- if (other.address != null) {
- return false;
- }
- } else if (!address.equals(other.address)) {
- return false;
- }
- return true;
- }
- }
调用即可
- private static List<User> removeListDuplicateObject(List<User> list) {
- System.out.println(Arrays.toString(list.toArray()));
- Set<User> set = new HashSet<User>();
- set.addAll(list);
- System.out.println(Arrays.toString(set.toArray()));
- List<User> listnewList = new ArrayList<User>(set);
- return listnewList;
- }