可比是原始类型。泛型类型Comparable <t>的引用应参数化

时间:2018-12-20 06:08:37

标签: java generics lambda functional-programming

我将变量设置为

Map<String, Function<CLASS_NAME, Comparable>> map = new HashMap<>();

其中Comparable给出警告消息为

Comparable is a raw type. References to generic type Comparable<T> should be parameterized

我正在使用它

map.put(VARIABLE_NAME1, s -> s.getStringProperty());
map.put(VARIABLE_NAME2, s -> s.getIntProperty());
..

我正在像进行比较

Comparator<CLASS_TYPE> v = Comparator.comparing(map.get(VARIABLE_NAME), Comparator.nullsFirst(Comparator.naturalOrder()));

应该使用哪种类型的泛型来避免警告?

2 个答案:

答案 0 :(得分:0)

可比显然是通用类型。

所以您只需要:

Map<String, Function<CLASS_NAME, Comparable<CLASSNAME>>> map = new HashMap<>();

代替

Map<String, Function<CLASS_NAME, Comparable>> map = new HashMap<>();

还是您要比较另一种类型??

Map<String, Function<CLASS_NAME, Comparable<SomeOtherClass>>> map = new HashMap<>();

答案 1 :(得分:0)

您当前的方案有很多问题。

  1. ComparatorComparable是比较对象的两种不同方法。您正在混淆两者。
  2. 您正在尝试存储将比较功能映射到地图中的功能。稍后,您从映射中获取值,然后尝试将其(函数)与Comparator进行比较。这将无法正常工作,因为您无法将一个功能与另一个功能进行比较。
  3. 您实际上不在任何地方存储值;您只存储一个函数。
  4. 在您的示例中,您将两个不同的值存储到同一VARIABLE_NAME中。那是故意的吗?

如果要创建属性映射,则需要创建一个可存储的对象,该对象可以存储到该映射中,并且可以将其值与提供的值进行比较。例如,

class Storable<T extends Comparable<T>> {
  private final T value;
  Storable(T value) {
    this.value = value;
  }
  int compareTo(Object other) {
    if ( value.getClass().equals(other.getClass()) ) {
      return value.compareTo( (T) other );
    }
    return -1;
  }
}

现在创建适当的子类:

class StorableInt extends Storable<Integer> {
    StorableInt(Integer t) {
        super(t);
    }
}
class StorableString extends Storable<String> {
    StorableString(String s) {
        super(s);
    }
}

您的财产地图现在看起来像:

Map<String, Storable<?>>map = new HashMap<>();

map.put(variableName1, new StorableInt(13));
map.put(variableName2, new StorableString("string2"));

<T extends Comparable<T>> int compare( String key, T val ) {
  return map.get( key ).compareTo( val );
}

您现在可以将属性存储到地图中,并与这些属性比较值。