我有两个具有相同名称但包含不同年龄(值)的对象,我尝试将这些对象添加到地图中以删除重复但不会删除。这是我正在测试的型号代码:
two ab = new two("john", "20");
two ac = new two("chan", "30");
two ad = new two("john", "34");
ArrayList<two> ae = new ArrayList<>();
public void adding(){
ae.add(ab);
ae.add(ac);
ae.add(ad);
System.out.println(ae);
}
public void removeDuplicate(){
Set<two> lhs = new HashSet<>();
lhs.addAll(ae);
ae.clear();
ae.addAll(lhs);
System.out.println(ae);
}
public static void main(String args[]){
one five = new one();
five.adding();
five.removeDuplicate();
}
这是用于对象类型的类:
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
}
结果是:
[john, chan, john]
[chan, john, john]
我还尝试将toString
仅返回名称,但用于删除重复项的地图似乎在这种情况下仍无效。我不明白,我无法确定潜在的问题。任何帮助表示赞赏。
答案 0 :(得分:0)
您必须覆盖equals
中的hashcode
和two
方法。
等于应该仅根据name
字段给出结果,并且还应仅使用name
字段形成哈希码,这将帮助您实现目标。
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
@Override
public boolean equals(Object obj){
if(obj==null)
return false;
if(name==null){
return false;
}
if(!(obj instanceof two)){
return false;
}
two another = (two)obj;
return this.name.equals(another.name);
}
public int hashCode(){
return name==null?0:name.hashCode();
}
}