pengguang001
pengguang001

Reputation: 4205

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.

Upvotes: 14

Views: 18773

Answers (5)

deepkimo
deepkimo

Reputation: 3197

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

Upvotes: 6

Denis Lukenich
Denis Lukenich

Reputation: 3164

If you want a SortedList you can for example take a list and manually call Collections.sort() after each insert.

Or you wrap e.g. an ArrayList to ensure the sort-calls for you:

    class SortedArrayList extends ArrayList<String> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void add(int index, String element) {
        super.add(index, element);
        Collections.sort(this);
    }

    @Override
    public boolean add(String element) {
        boolean returnValue = super.add(element);
        Collections.sort(this);
        return returnValue;
    }

    @Override
    public boolean addAll(Collection<? extends String> c) {
        boolean returnValue = super.addAll(c);
        Collections.sort(this);
        return returnValue;
    }

    @Override
    public boolean addAll(int index, Collection<? extends String> c) {
        boolean returnValue = super.addAll(index, c);
        Collections.sort(this);
        return returnValue;
    }

    @Override
    public String set(int index, String element) {
        String returnValue = super.set(index, element);
        Collections.sort(this);
        return returnValue;
    }
}

I hope I got all functions which can require sorting. (Remove is not necessary to override)

Upvotes: 2

Andrey Adamovich
Andrey Adamovich

Reputation: 20663

A quote from Javadoc for Set:

A collection that contains no duplicate elements

Use any derivative of List.

Upvotes: 3

Alan Escreet
Alan Escreet

Reputation: 3549

A main purpose of a Set is to not have duplicates. You either don't want a Set or you need a different Comparator.

Upvotes: 4

Heiko Rupp
Heiko Rupp

Reputation: 30934

A set by definition can not have duplicate entries.

So you need to use a List or Array or such

Upvotes: 10

Related Questions