开发者

java TreeSet - don't remove duplicate items

开发者 https://www.devze.com 2023-03-02 19:36 出处:网络
TreeSet removes different i开发者_StackOverflowtems with the same Comprator value. I don\'t want it be removed.

TreeSet removes different i开发者_StackOverflowtems 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.


A set by definition can not have duplicate entries.

So you need to use a List or Array or such


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


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


A quote from Javadoc for Set:

A collection that contains no duplicate elements

Use any derivative of List.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号