How to distinguish between two equal objects in a sorted collection?

Maybe I'm wrong, but for me we can redefine the equals for the object, so that you consider them significant equal. The entire record on the card has different keys, and all the records in the set have different values ​​(it makes no sense)

But when using TreeMap or TreeSet you can provide a comparator. I noticed that when a comparator is provided, the object is equal to the method that bypasses, and two objects are considered equal when the comparator returns 0. Thus, we have 2 objects, but only one is stored inside the map set or set.

I would like to know if it is possible, using a sorted collection, to distinguish between two different instances.

Here is a simple example:

public static void main(String[] args) {
    TreeSet<String> set = new TreeSet<String>();
    String s1 = new String("toto");
    String s2 = new String("toto");
    System.out.println(s1 == s2);
    set.add(s1);
    set.add(s2);
    System.out.println(set.size());
}

, String ( "xxx" ) , s1!= s2. , , 2, 1.

: String, -!= 0 ?

, , :

. , , , . , sgn (compare (x, y)) == -sgn (. (Y, x)) x y. ( , compare (x, y) , compare (y, x) .)

, : ((. (x, y) > 0) && (. (y, z) > 0)) (x, z) > 0.

, , compare (x, y) == 0 , sgn (compare (x, z)) == sgn (compare (y, z)) z.

, , (. (x, y) == 0) == (x.equals(y)). , , , . : ": , ".

:

public int compare(String s1,String s2) {
  if s1.equals(s2) { return -1 }
  ...
}

, , , (s1, s2)!= -compare (s2, s1)

, ?


: , , . , .

:

, :

class Label {
  String label;
}

String. , , label- > value. , , ? "label" (ref1) → value1 "label" (ref2) → value2 equals , Label → , HashMap.

, , Label ? . , ? ! compare (ref1, ref2) 0. -1 1? - , , , Java...

+3
6

Guava, Ordering.arbitrary(), , . .

. Multiset (, TreeMultiset), ?

+6

( ):

Comparator<String> comp = Ordering.natural().compound(Ordering.arbitrary());

, , , .

+3

, . javadoc Comparator:

, ( ). , ( ) c ( ), S. , c S, , set ( ) "". , set ( ) ( map), .

+2

, Collections.sort().

0

, SortedSet<Collection<String>> , , , .

Guava MultiSet.

JavaDoc SortedSet:

, , ( ), , Set.

: , ( equals()).

0

0 , , :

public int compare(String s1,String s2) {
   if (s1!=s2) { 
      int result = s1.compareTo(s2);
      if (result == 0) {
          return -1;
      } else {
          return result;
      }
   } else {
      return 0;
   } 
}
-2

All Articles