gpt4 book ai didi

java - 从列表中删除重复的集

转载 作者:行者123 更新时间:2023-11-30 04:01:56 25 4
gpt4 key购买 nike

我正在尝试从 ArrayList 中删除重复的自定义对象集。下面是我编写的代码,它使用自定义 EmployeeObj 的 toString 表示形式进行比较。您能否建议可以采取哪些其他方法?

package com.collections;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DupSetInsideList {
public static void main(String[] args) {
List<Set<EmployeeObj>> list = new ArrayList<Set<EmployeeObj>>();

Set<EmployeeObj> set1 = new HashSet<EmployeeObj>();
Set<EmployeeObj> set2 = new HashSet<EmployeeObj>();
Set<EmployeeObj> set3 = new HashSet<EmployeeObj>();

list.add(set1);
list.add(set2);
list.add(set3);

EmployeeObj empObj1 = new EmployeeObj(1, "Nikhil");
EmployeeObj empObj2 = new EmployeeObj(2, "Rakesh");
EmployeeObj empObj3 = new EmployeeObj(3, "Kunal");

set1.add(empObj1);
set1.add(empObj2);

set2.add(empObj1);
set2.add(empObj2);

set3.add(empObj1);
set3.add(empObj2);
set3.add(empObj3);

System.out.println("List with duplicaes: " + list);
//Output: List with duplicaes: [[1=Nikhil, 2=Rakesh], [1=Nikhil, 2=Rakesh], [3=Kunal, 1=Nikhil, 2=Rakesh]]

//Remove duplicates
List<Set<EmployeeObj>> nonDupList = new ArrayList<Set<EmployeeObj>>();
for(Set<EmployeeObj> obj1:list) {
if(!nonDupList.contains(obj1)) {
nonDupList.add(obj1);
}
}
System.out.println("List without duplicates: " + nonDupList);
//List without duplicates: [[1=Nikhil, 2=Rakesh], [3=Kunal, 1=Nikhil, 2=Rakesh]]
}
}

class EmployeeObj {
private int id;
private String name;

public int getId() {
return id;
}

public String getName() {
return name;
}


public EmployeeObj(int id, String name) {
this.id = id;
this.name = name;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.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;
EmployeeObj other = (EmployeeObj) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

@Override
public String toString() {
return id + "=" + name;
}
}

最佳答案

如果您希望列表行为保证元素的唯一性,请使用 LinkedHashSet 而不是 ArrayList

如果您一定要使用ArrayList(如学生练习中那样),请扩展它,通过检查来覆盖addaddAll方法首先是唯一性,然后分别调用 super.addsuper.addAll,然后使用新类代替 ArrayList

关于java - 从列表中删除重复的集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21774450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com