【发布时间】:2014-12-27 10:15:59
【问题描述】:
我必须使用HashSet,其中可能会插入大量重复值。但是我想在以后的插入产生重复时保留在哈希中插入的早期数据。为了检查这一点,我编写了以下代码并插入了许多重复值,但这并不能让我满意。请看下面的代码 -
import java.util.HashSet;
import java.util.Set;
public class SetTest {
private static Set<Student> studentSet = new HashSet<Student>();
private static Student s1, s2, s3, s4, s5, s6, s7, s8, s9;
public static void main(String args[]){
s1 = new Student(1, 1, "Syeful", "first boy");
s2 = new Student(2, 2, "Razib", "no comments");
s3 = new Student(3, 3, "Bulbul", "should remain");
s4 = new Student(4, 3, "Bulbul", "should not remain");
s5 = new Student(5, 4, "Bulbul", "should remain");
s9 = new Student(9, 5, "Proshanto", "kaka - my favourite");
studentSet.add(s1);
studentSet.add(s2);
studentSet.add(s3);
studentSet.add(s4);
studentSet.add(s5);
studentSet.add(s9);
for(Student each : studentSet){
System.out.println("SrNo: " +each.getSrNo()+ " roleNo: "
+each.getRoleNo()+ " name: " +each.getName()+
" coment: " +each.getComment());
}
}
}
class Student{
private int srNo;
private int roleNo;
private String name;
private String comment;
public Student(int srNo, int role, String name, String comment) {
super();
this.srNo = srNo;
this.roleNo = role;
this.name = name;
this.comment = comment;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + roleNo;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (roleNo != other.roleNo) {
return false;
}
return true;
}
public int getSrNo() {
return srNo;
}
public int getRoleNo() {
return roleNo;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
}
输出是:
Set Size: 5
SrNo: 9 roleNo: 5 name: Proshanto coment: kaka - my favourite
SrNo: 2 roleNo: 2 name: Razib coment: no comments
SrNo: 1 roleNo: 1 name: Syeful coment: first boy
SrNo: 5 roleNo: 4 name: Bulbul coment: should remain
SrNo: 3 roleNo: 3 name: Bulbul coment: should remain
在提问之前,我似乎先澄清了一些观点,以便我能够正确解释并澄清我的理解。
我想根据
roleNo和name保持'Student' 的唯一性。这就是为什么hashCode() 和equals() 角色是由这些属性组成的。所以根据这个实现 s3 和 s4 是彼此重复的,即使它们的comment,srNo属性彼此不同。HashSet是无序的。当 s4 添加到集合中时,我们可以从输出中看到 s4 从集合中被丢弃,而 s3 仍然存在。
假设我想添加另一个学生
s100 = new Student(3, 3, "Bulbul", "earlier instance suppressed");的对象,它是 s3 的副本。让我们在插入 s100 之前插入了很多重复的 s3。
问题:
由于 set 是未排序的,并且 set 中不存在重复的剂量,所以 s3 是否有可能被 s100 删除?我想保留较早的对象而丢弃较晚的对象。少量的数据并不能说明事实。我认为在这种情况下可以使用排序的Set。但是HashSet 可以达到目的吗?
提前致谢。
【问题讨论】:
标签: java hash collections set hashset