简体   繁体   中英

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 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");
      }
    });
  }
}

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 (ie Comparable), but not both at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM