Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3480624
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T10:22:17+00:00 2026-05-18T10:22:17+00:00

Suppose I need TreeSet with elements sorted with some domain logic. By this logic

  • 0

Suppose I need TreeSet with elements sorted with some domain logic. By this logic it doesn’t matter order of some elements that doesn’t equal so compare method can return 0, but in this case I couldn’t put them in TreeSet.

So, question: what disadvantages I’ll have from code like this:

class Foo implements Comparable<Foo>{}
new TreeSet<Foo>(new Comparator<Foo>(){
    @Override
    public int compare(Foo o1, Foo o2) {
        int res = o1.compareTo(o2);
        if(res == 0 || !o1.equals(o2)){
            return o1.hashCode() - o2.hashCode();
        }
        return res;
    }
});

Update:

Ok. If it should always be a consistency between the methods equals(), hashcode() and compareTo(), as @S.P.Floyd – seanizer and others said.
If it would be better or even good if I’ll remove Comparable interface and move this logic in Comparator (I can do it without broken encapsulation)? So it will be:

class Foo{}
new TreeSet<Foo>(new Comparator<Foo>(){
    @Override
    public int compare(Foo o1, Foo o2) {
        //some logic start
        if(strictliBigger(o1, o2)){ return 1;}
        if(strictliBigger(o2, o1)){ return -1;}
        //some logic end
        if(res == 0 || !o1.equals(o2)){
            return o1.hashCode() - o2.hashCode();
        }
        return res;
    }
});

Update 2:

Would System.identityHashCode(x) be better than hashCode() if I don’t need stable sort?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T10:22:17+00:00Added an answer on May 18, 2026 at 10:22 am

    While this might work, it is far from being a best practice.

    From the SortedSet docs:

    Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

    For objects that implement Comparable, there should always be a consistency between the methods equals(), hashcode() and compareTo().


    I’m afraid a SortedSet is just not what you want, nor will a Guava MultiSet be adequate (because it will not let you independently retrieve multiple equal items). I think what you need is a SortedList. There is no such beast that I know of (maybe in commons-collections, but those are a bit on the legacy side), so I implemented one for you using Guava’s ForwardingList as a base class. In short: this List delegates almost everything to an ArrayList it uses internally, but it uses Collections.binarySearch() in it’s add() method to find the right insertion position and it throws an UnsupportedOperationException on all optional methods of the List and ListIterator interfaces that add or set values at a given position.

    The Constructors are identical to those of ArrayList, but for each of them there is also a second version with a custom Comparator. If you don’t use a custom Comparator, your list elements need to implement Comparable or RuntimeExceptions will occur during sorting.

    public class SortedArrayList<E> extends ForwardingList<E> implements
        RandomAccess{
    
        private final class ListIteratorImpl extends ForwardingListIterator<E>{
            private final int start;
            public ListIteratorImpl(final int start){
                this.start = start;
            }
    
            @Override
            public void set(E element){throw new UnsupportedOperationException();}
    
            @Override
            public void add(E element){throw new UnsupportedOperationException();}
    
            @Override
            protected ListIterator<E> delegate(){return inner.listIterator(start);};
    
        }
    
        private Comparator<? super E> comparator;
    
        private List<E> inner;
    
        public SortedArrayList(){this(null, null, null);}
    
        @SuppressWarnings("unchecked")
        private SortedArrayList(
            final List<E> existing,
            final Collection<? extends E> values,
            final Comparator<? super E> comparator
        ){
            this.comparator =
                (Comparator<? super E>)
                   (comparator == null
                       ? Ordering.natural()
                       : comparator   );
            inner = (
                existing == null
                    ? (values == null
                          ? new ArrayList<E>(values)
                          : new ArrayList<E>()
                       )
                    : existing;
        }
    
        public SortedArrayList(final Collection<? extends E> c){
            this(null, c, null);
        }
    
        public SortedArrayList(final Collection<? extends E> c,
            final Comparator<? super E> comparator){
            this(null, c, comparator);
        }
    
        public SortedArrayList(final Comparator<? super E> comparator){
            this(null, null, comparator);
        }
    
        public SortedArrayList(final int initialCapacity){
            this(new ArrayList<E>(initialCapacity), null, null);
        }
    
        public SortedArrayList(final int initialCapacity,
            final Comparator<? super E> comparator){
            this(new ArrayList<E>(initialCapacity), null, comparator);
        }
    
        @Override
        public boolean add(final E e){
            inner.add(
                Math.abs(
                    Collections.binarySearch(inner, e, comparator)
                ) + 1,
                e
            );
            return true;
        }
    
        @Override
        public void add(int i, E e){throw new UnsupportedOperationException();}
    
        @Override
        public boolean addAll(final Collection<? extends E> collection){
            return standardAddAll(collection);
        }
    
        @Override
        public boolean addAll(int i,
            Collection<? extends E> es){
            throw new UnsupportedOperationException();
        }
    
        @Override
        protected List<E> delegate(){ return inner; }
    
        @Override
        public List<E> subList(final int fromIndex, final int toIndex){
            return new SortedArrayList<E>(
                inner.subList(fromIndex, toIndex),
                null,
                comparator
            );
        }
    
        @Override
        public ListIterator<E> listIterator(){ return new ListIteratorImpl(0); }
    
        @Override
        public ListIterator<E> listIterator(final int index){
            return new ListIteratorImpl(index);
        }
    
        @Override
        public E set(int i, E e){ throw new UnsupportedOperationException(); }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose you have two seperate ASP.NET Web Application projects that both need to use
I need to construct some rather simple SQL, I suppose, but as it's a
Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new
Suppose I need to set an opacity mask on a WPF control that highlights
Suppose I need to run this on shell, $ su <user>; cp /x /y;
Suppose you need to check some condition at multiple places in code. For ex.
I have a buzz to solve and need some help. Suppose I have a
Suppose you need to run a program on the world’s fastest supercomputer which will
Suppose you have a collection of a few hundred in-memory objects and you need
I need to write a java script. This is supposed to validate if the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.