开发者

Invoke Arrays.sort( array, comparator ) using generics problem

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 excepti开发者_JAVA技巧on 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");
      }
    });
  }
}


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜