Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java TreeSet - don't remove duplicate items

TreeSet removes different items with the same Comprator value. I don't want it be removed. Is there any way to control this? Or use another container class?

Added: OK. It seems I can't use Set. I need insert sorting feature, for performance consideration. Can List do this? Thanks all.

like image 354
pengguang001 Avatar asked May 05 '11 09:05

pengguang001


2 Answers

A set by definition can not have duplicate entries.

So you need to use a List or Array or such

like image 69
Heiko Rupp Avatar answered Oct 09 '22 20:10

Heiko Rupp


Even it is a set, this is still confusing because the objects are different. For example, a Set<E> of different objects E will drop some objects when converted to a TreeSet<E> based on the Comparator<E> used. In both cases, it is a set, but the set of elements stored will be different. In my opinion this is not clarified well in the docs.

A simple solution, if you can change the Comparator, let it not return 0. For example instead of:

public int compare(Integer o1, Integer o2) {
    return o1.compareTo(o2);
}

Use:

public int compare(Integer o1, Integer o2) {
    return o1 < o2 ? -1: 1;
}
like image 43
deepkimo Avatar answered Oct 09 '22 18:10

deepkimo