Reputation:
I need to have data structure like HashSet
.
As I understand HashSet
calculates hashCode
at first, if hashCode
is the same it checks equals
method if true than it will not add an item, otherwise item with the same hashCode
but another equals
will be added to the bucket linked list.
What I need to do is just keep only unique objects like Set
does, but using equals
method only, and if objects are equal than increment counter associated with each object.
Is there any such data structure already implemented, or I should create my own ?
Upvotes: 1
Views: 1168
Reputation: 72854
The simplest way (without dependecies) is to have a HashMap<Element, Integer>
. Or you can use Guava's MultiSet
which has a count(Object)
method to get the number of occurrences of an object in the collection.
Upvotes: 1
Reputation: 11655
It seems that what you really need is a map. For every item you can have the number of items
public class ItemCounter<T>{
private Map<T, Integer> counts = new HashMap<T, Integer>();
public void addItem(T item){
Integer numberOfOcurrences = counts.get( item );
numberOfOcurrences = numberOfOcurrences == null ? 0 : numberOfOcurrences+1;
counts.put( item, numberOfOcurrences);
}
public Integer getCount( T item ){
Integer numberOfOcurrences = counts.get( item );
return numberOfOcurrences == null ? 0 : numberOfOcurrences;
}
}
Upvotes: 3