Java HashSet using a specified method
Posted
by
threenplusone
on Stack Overflow
See other posts from Stack Overflow
or by threenplusone
Published on 2011-01-02T02:38:53Z
Indexed on
2011/01/02
2:54 UTC
Read the original article
Hit count: 272
I have a basic class 'HistoryItem' like so:
public class HistoryItem
private Date startDate;
private Date endDate;
private Info info;
private String details;
@Override
public int hashCode() {
int hash = (startDate == null ? 0 : startDate.hashCode());
hash = hash * 31 + (endDate == null ? 0 : endDate.hashCode());
return hash;
}
}
I am currently using a HashSet to remove duplicates from an ArrayList on the startDate & endDate fields, which is working correctly.
However I also need to remove duplicates on different fields (info & details).
My question is this.
Is there a way to specify a different method which HashSet will use in place of hashCode()?
Something like this:
public int hashCode_2() {
int hash = (info == null ? 0 : info.hashCode());
hash = hash * 31 + (details == null ? 0 : details.hashCode());
return hash;
}
Set<HistoryItem> removeDups = new HashSet<HistoryItem>();
removeDups.setHashMethod(hashCode_2);
Or is there another way that I should be doing this?
© Stack Overflow or respective owner