假设我有一个自定义数据类型:
public class Notification {
private String name;
private String location;
private String message;
// Constructors, getter, setters, etc.
}
我想从列表中将对象(
Notification
类型)添加到集合中,以消除重复项。但是仅仅将它们添加到Set中是行不通的,因为Java不知道如何检查是否存在重复项。我如何告诉Java,当我向集合中添加
Notification
对象时,我希望它仅检查name
属性是否唯一(忽略其他字段)?
最佳答案
我发现使用Louis Wasserman提到的Map(按名称属性键)比覆盖hashChode和equals更好。如果您要尝试做我正在做的事情,则可以实现以下内容:
Map<String, Notification> m = new HashMap();
for (Notification n : notifications) {
m.put(n.getHostname(), n);
}
Iterator it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
遍历Map时,您会看到它根据键确定对象是否唯一!比使用Set容易得多。
关于java - 是否基于自定义属性将用户定义的数据类型添加到Java集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487293/