HashSet with number of occurences

Hi,

I use an HashSet to store some objects without repetitions,

is there a way to count how many times a specific object has occured?

I better explain:

the main app. finds an object, it tries to store it into the hashset,

so only one istance for each type of object is stored, although I find many copies of the same type of obj.

I wanna be able to count how many times it happens for each type of obj in the most efficient way.

Could you help me?

Thanks!

by

[520 byte] By [Jocoa] at [2007-11-27 8:32:33]
# 1
Use a HashMap. The Object is the key, and a counter is the value.Kaj
kajbja at 2007-7-12 20:28:26 > top of Java-index,Java Essentials,Java Programming...
# 2

As always, be sure your "objects" have appropriately defined hashCode and equals methods:

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

Demo:

import java.util.*;

public class MapExample {

private Map < String, Integer > wordCounts = new HashMap < String, Integer > ();

public void increment(String key) {

Integer count = wordCounts.get(key);

if (count == null)

count = 0;

wordCounts.put(key, 1 + count);

}

public String toString() {

return wordCounts.toString();

}

public static void main(String[] args) {

MapExample app = new MapExample();

app.increment("one");

app.increment("two");

app.increment("three");

app.increment("four");

app.increment("two");

app.increment("three");

app.increment("four");

app.increment("three");

app.increment("four");

app.increment("four");

System.out.println(app);

}

}

Message was edited by:

Hippolyte

Hippolytea at 2007-7-12 20:28:26 > top of Java-index,Java Essentials,Java Programming...