Re: Collection of distinc objects
Hello,
Many thanks for you code. I'm especially interested in this:
[...]
public class InstanceComparator<T> implements Comparator<T> {
private int next = 0;
public int compare (T t1, T t2) {
int i = getID(t1);
int j = getID(t2);
return (i < j)?-1:((i > j)?1:0);
}
private WeakHashMap<Holder<T>, Integer> map = new
WeakHashMap<Holder<T>, Integer>();
private int getID (T t) {
Holder<T> h = new Holder<T>(t);
Integer i = map.get(h);
if (i != null) return i.intValue();
map.put(h, Integer.valueOf(next));
return next++;
}
}
I planed to do it in the same way. But I thought it wouldn't work so I
dropped it.
Is it working ??? WeakHashMap is holding Holders. They have strong
references to something, but those Holders are not strongly referenced
anywhere. I think they will by collected by GC, despite their contents. Then
we loose information about assigned IDs. Numbers will be generated all the
time, even for objects which where compared before.
Am I right ?
Regards
Dz