1

I'm trying to create a method which in turn should call Arrays.sort method and I'm trying this method to be generic itself. The problem comes when I try to create a concrete Comparator but I always get one exception like:

Generics.java:15: cannot find symbol
symbol  : method sort(java.lang.Comparable[],java.util.Comparator<T>)
location: class java.util.Arrays
                Arrays.sort(array,  c);
                      ^
1 error

I workaround it by casting the value, but I would really like to know how to code it properly.

Here's my ( relevant ) code:

import java.util.*;
abstract class Generics<T1,T2> { 

  public abstract  void run( T1 a , T2 b );

  public static <T> void sort( Comparable[] array, final Generics<T,T> g  ) {

    Comparator<T> c = new Comparator<T>() {
      public int compare(T o1, T o2) {
        g.run(o1,o2);
        return 1;
      }
    };
    Arrays.sort(array, 
      /* how can I get rid of this cast? */ 
      (Comparator<? super Comparable>)
      /* and use only */ c);
  }

  public static void main( String ... args ) { 
    Generics.sort( args, new Generics<String,String>() { 
      public void run( String a, String b ) { 
        System.out.println( "Irrelevant");
      }
    });
  }
}
2
  • Also note that your Comparator implementation (with return 1) does not fulfill the contract of the interface (antisymmetry, reflexivity). I suppose this is only for testing purposes. Commented May 24, 2011 at 23:08
  • Yeap, that part is not relevant to the problem. Thanks again. Commented May 24, 2011 at 23:09

1 Answer 1

6

Your method should not pass a Comparable[], but a T array, if you want to use a Comparator<T>.

Thus define it this way:

public static <T extends Comparable<T>> void sort( T[] array, final Generics<T,T> g  ) {
    ...
}

But why do you want to use both Comparable and Comparator? Normally the idea is to either use the Comparator or the default order on the element (i.e. Comparable), but not both at once.

Sign up to request clarification or add additional context in comments.

2 Comments

I struggle with this for ... hours! :) :) Thans a lot Paulo!
+1: But as it makes little sense to use both Comparable and Comparator, you don't need the "extends Comparable<T>".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.