0

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?

1
  • 1
    We call that "thing" a class. And the language is Java, not JAVA. Commented Oct 23, 2009 at 3:51

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If your key is the number, what you really want as the value is just the count of how many are found.
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...
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.
6

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;
  }
}

1 Comment

You could even override add and delete to create an entry at that key if it didn't exist, and increment if it did.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.