1

I have a Shape class and in this class there is a method called getRepr() that can get a char representation of a shape. For example,

ShapeA.getRepr() ->'a' 
ShapeB.getRepr() ->'b'
ShapeC.getRepr() ->'c'

Now I have an ArrayList that stores several shapes including ShapeE, ShapeA, ShapeD, ShapeC, and ShapeB.

The question is how can I use Collections.sort() to alphabetically rearrange these shapes in the ArrayList according to their char representations?

The expected result in this ArrayList after sorting should be ShapeA, ShapeB, ShapeC, ShapeD, ShapeE.

Or is there a way to reach this purpose without Collections.sort()?

jadhachem
  • 1,123
  • 2
  • 11
  • 19
user4593157
  • 85
  • 1
  • 2
  • 9

3 Answers3

5

you need to implement Comparable interface in your SuperClass

public class MyClassSuperClass implements Comparable<MyClassSuperClass>{

    @Override
    public int compareTo(MyClassSuperClass o) {
        return this.getRepr().compareTo(o.getRepr());
    }


}

Then you can just call the .sort method on your collection

  1. if obj a>b the compareTo shall return a value > 0
  2. if obj a
  3. if obj a == b the compareTo shall return 0

For the mathematically inclined, the relation that defines the natural ordering on a given class C is:

   {(x, y) such that x.compareTo(y) <= 0}.   The quotient for this total order is:
   {(x, y) such that x.compareTo(y) == 0}.   It follows immediately from the contract for compareTo that the quotient is an

equivalence relation on C, and that the natural ordering is a total order on C. When we say that a class's natural ordering is consistent with equals, we mean that the quotient for the natural ordering is the equivalence relation defined by the class's equals(Object) method: {(x, y) such that x.equals(y)}.

for more information please check this link:

https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

0

This has already been answered here: Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

Collections.sort(list,
             new Comparator<String>()
             {
                 public int compare(String s1, String s2)
                 {
                     return s1.compareTo(s2);
                 }        
             });
Community
  • 1
  • 1
Forseth11
  • 1,418
  • 1
  • 12
  • 21
  • 1
    Note that this just compares two Strings (not two Shapes) by their natural ordering, for which you don't actually need a custom Comparator (you can just do `Collections.sort(list)` and get the same result). – yshavit Apr 23 '15 at 01:31
  • @yshavit is right here. And you don't need a custom `Comparator`, because your current type `String` already implements the `Comparable` interface, so it will take care about comparing itself with another String instance. – Tom Apr 23 '15 at 01:33
0

You can use Comparable/Comparator to achieve this, check this link for detailed info Object Ordering

Sunil Rajashekar
  • 350
  • 2
  • 18