【发布时间】:2014-01-28 00:05:37
【问题描述】:
所以我有一个旧列表、一个新列表和一个唯一列表。我从每个列表(旧/新)中读取数据,并从我的类文件中创建一堆对象。然后我将 newList 添加到唯一用户,然后删除旧列表以确定唯一用户。
类
public class User {
private String fName;
private String mInitial;
private String lName;
private String age;
private String city;
private String state;
... // set and get methods
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((fName == null) ? 0 : fName.hashCode());
result = prime * result + ((lName == null) ? 0 : lName.hashCode());
result = prime * result
+ ((mInitial == null) ? 0 : mInitial.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if(o == null) return false;
if (getClass() != o.getClass()) return false;
User other = (User) o;
if(this.fName != other.fName) return false;
if(! this.mInitial.equals(other.mInitial)) return false;
if(! this.lName.equals(other.lName)) return false;
if(! this.age.equals(other.age)) return false;
if(! this.city.equals(other.city)) return false;
if(! this.state.equals(other.state)) return false;
return true;
}
}
主要
try {
// List creation (new, old, unique)
List<User> listNew = new ArrayList<User>();
List<User> listOld = new ArrayList<User>();
Collection<User> listUnique = new HashSet<User>();
// Read the files in with while loop,
// ...
// Put them in their respective list
// ...
listUnique.addAll(listNew);
System.out.println("Junk... " + listUnique.size());
listUnique.removeAll(listOld);
// Checking the sizes of lists to confirm stuff is working or not
System.out.println(
"New: \t" + listNew.size() + "\n" +
"Old: \t" + listOld.size() + "\n" +
"Unique: " + listUnique.size() + "\n"
);
}
catch { ... }
输出
Junk... 20010
New: 20010
Old: 20040
Unique: 20010
所以基本上它是将内容添加到列表中,但 removeAll 不起作用。这可能是我的用户类文件中的 hashCode() 的问题吗?我只是无法弄清楚为什么它不起作用。 (注意:我在类文件中自动生成了我的 hashCode,不确定这是不是一个坏主意)
感谢您的帮助!
【问题讨论】:
-
if(this.fName != other.fName) return false;让我印象深刻。 -
为什么你会选择与
!=进行6个字符串比较中的1个? -
鉴于我对创建自己的 equals/hashCode 方法不是很熟悉,所以我使用了本指南:tutorials.jenkov.com/java-collections/hashcode-equals.html .. 所以您认为我应该将其更改为与其他方法相同吗?