Java Comparing Generics with Comparable<? super T> from another class

aarbor :

I have a "Schema" and "Field" model in which a Field represents a data type and has methods on how to parse it, and the schema is a collection of fields. I am trying to implement generic comparison, however, I can't get the code to compile and I can't figure out the proper generic scopes. How can I get this to work?

class Field<T extends Comparable<? super T>> {

  T parse(String val) {
  ... 
  }
}

public class Schema {
  Map<Integer, Field<?>> fields;

  Field<?> getField(int index){ ... }
}

public class Comparison {
  public static <T extends Comparable<? super T>> boolean greaterThan(Field<T> f, String val1, String val2) {
   // compiles as expected
    return f.parse(val1).compareTo(f.parse(val2)) > 0;
  }

  public static boolean greaterThan2(Field<?> f, String val1, String val2) {
   // does not compile -> required capture of ? super capture of ?, provided capture of ? 
   return f.parse(val2).compareTo(f.parse(val2));
  }
}

public class App {

 public static void main(String[] args) {
  Schema s = ...
  // does not compile, required type Field<T>, provided type Field<capture of ?>
  Comparison.greaterThan(s.getField(0), "val1", "val2");
  // compiles
  Comparison.greaterThan2(s.getField(0), "val1","val2");
}
}

Jags :

Below code compiles in 1.8

import java.util.Map;

class Field<T extends Comparable<? super T>> {

  T parse(String val) {
      return null;
  }
}

class Schema {
  Map<Integer, Field<?>> fields;

  Field<?> getField(int index){ return null; }
}

class Comparison {
  public static <T extends Comparable<? super T>> boolean greaterThan(Field<T> f, String val1, String val2) {
   // compiles as expected
    return f.parse(val1).compareTo(f.parse(val2)) > 0;
  }
}

public class App {

 public static void main(String[] args) {
  Schema s = new Schema();
  //compiles ok
  Comparison.greaterThan(s.getField(0), "val1", "val2");
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20932&siteId=1