[英]How to remove duplicates in the Java HashSet
I have a set of this structure. 我有一套这样的结构。 How to remove duplicates of equal object of that class? 如何删除该类相等对象的重复项? Equals means field File plik is the same. 等于表示字段文件plik相同。
EDIT: But the problem gut bigger I don't have duplicates but I would like to replace old SET member by new. 编辑:但是问题更大,我没有重复,但是我想用新的替换旧的SET成员。
Withoud 3rd party libraries. 第三党图书馆。
import java.io.*;
public class WordInfo implements Serializable {
File plik;
Integer wystapienia;
public WordInfo(File plik, Integer wystapienia) {
this.plik = plik;
this.wystapienia = wystapienia;
}
public String toString() {
// if (plik.getAbsolutePath().contains("src") && wystapienia != 0)
return plik.getAbsolutePath() + "\tWYSTAPIEN " + wystapienia;
// return "";
}
}
I don't have this HashCodeBuilder I want to use Java standard libraries 我没有要使用Java标准库的HashCodeBuilder
public int hashCode() {
return new HashCodeBuilder(17, 31).append(plik).append(wystapienia).toHashCode();
}
public boolean equals(Object obj) {
File f = (File) obj;
return(plik.getAbsoluteFile().equals(f.getAbsolutePath()));
}
As discussed here , override equals. 作为讨论在这里 ,覆盖equals方法。
public class Person {
private String name;
private int age;
// ...
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != getClass())
return false;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
public class WordInfo implements Serializable {
File plik;
Considering that following is how you can override the equals
and hashCode
method as per your requirement: 考虑到以下内容,您可以根据需要重写equals
和hashCode
方法:
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(!(obj instanceof WordInfo)) return false;
return this.plik.equals(((WordInfo) obj).plik);
}
@Override
public int hashCode() {
return this.plik.hashCode();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.