views:

112

answers:

2

There is a class called HashSet in Java

For example, I'll add following int-shaped value to HashSet,

[input]

1,2,3,4,5,6,1,2,3,1,

[hash structure]

1,1,1
2,2
3,3
4
5
6

Is there the collection to become such a structure?

+6  A: 

No, but it's easy enough to wrap around a HashMap.

public class Tally<T> {
  private final Map<T, Integer> count = new HashMap<T, Integer>();

  public void increment(T t) {
    Integer i = count.get(t);
    count.put(t, i == null ? 1 : i+1);
  }

  public void decrement(T t) {
    Integer i = count.get(t);
    if (i == null) {
      throw new IllegalArgumentException("not present");
    }
    if (i == 1) {
      count.remove(t);
    } else {
      count.put(t, i-1);
    }
  }

  public int get(T t) {
    Integer i = count.get(t);
    return i == null ? 0 : i;
  }
}
cletus
You could even override add and delete to create an entry at that key if it didn't exist, and increment if it did.
Paul Tomblin
Isn't that what it's doing?
cletus
+6  A: 

If I understand your question properly, you're looking for what's called a "Multiset". Java has no builtin Multisets, but you could build what you want with a HashMap<Integer, HashSet<Integer>>. There's also a number of third-party libraries for this, such as the Google Collections Library.

bdonlan
If your key is the number, what you really want as the value is just the count of how many are found.
Paul Tomblin
It's unclear from the question whether he's really storing integers, or if he's storing some more complex objects, and just used integers as an example...
bdonlan
Actually, I'd say it is clear from the way that question is posed that the OP *expects* the data structure to hold multiple values, rather that indicative values (keys) and counts. Whether that is what he really needs is a different question of course.
Stephen C