Java HashSet using the specified method

I have a base class HistoryItem:

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 in the startDate and endDate fields that work correctly.

However, I also need to remove duplicates in different fields (information and details).

My question is this. Is there a way to specify another method that the HashSet will use instead of hashCode ()? Something like that:

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 I have to do this?

+3
source share
6 answers

I ended up using GNU Trove .

Minimal code change required.

A new class that implements TObjectHashingStrategy (containing HashCodeand methods Equals).

public class HistoryItemDuplicateInfo
implements TObjectHashingStrategy<HistoryItem> {

  @Override
  public int computeHashCode(HistoryItem obj) {
     ...
  }

  @Override
  public boolean equals(HistoryItem arg0, HistoryItem arg1) {
    ...
  }
}

THashSet .

THashSet<HistoryItem> hs = new THashSet<HistoryItem>(new HistoryItemDuplicateInfo());

, - .

+1

HistoryItem GetHashCode, HashSet .

+2

. , equals(), hashCode(). . -, , , , HashSet. , :

HashSet<String> info;
HashSet<String> details;
for (HistoryItem h:map){
  if(info.contains(h.getInfo()){
    // this is a dup

  }
  if (details.contains(h.getDetails()){
    // this is a dup
  }
  info.add(h.getInfo());
  details.add(h.getDetails());
}
+1

java.util.TreeSet Comparator, Info Details.

0

:

  • long Date.
  • , . ? , SortedSet, TreeSet Set, , LinkedHashSet.
  • HistoryItem , ? , ?
  • , hashCode/equals/compareTo, . ? , ?
0

HashSet hashCode() equals(). HashSet - , , Java, , , , Java ( JDK, Sun/Oracle JDK OpenJDK).

TreeSet. TreeSet compareTo() , hashCode() equals(). , TreeSet Comparator, , . compareTo() ( Comparator.compare()) , hashCode() -and- equals(), . TreeSet , , HashSet, , , .

, HashSet - Comparator: HasherAndEqualizer int hashCode(Object obj) boolean equals(Object obj1, Object obj2). Sun , . , , . "GNU Trove", , .

. HistoryItem HistoryItemWrapper, HistoryItem hashCode()/equals(), .

0

Source: https://habr.com/ru/post/1783050/


All Articles