简体   繁体   中英

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

I am setting my my variable like

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

where Comparable is giving the warning message as

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

I am using it like

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

I am using for compare like

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

What type of Generic should be used to avoid the warning?

Comparable is obviously a generic type.

So all you need is just:

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

instead of

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

or you want to compare another type..?

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

There are several things wrong with your current scheme.

  1. Comparator and Comparable are two different approaches to comparing objects. You are confusing the two.
  2. You are trying to store a function that does comparisons into the map. Later, you fetch the value from the map and try to compare it (the function) to a Comparator . This won't work, as you can't compare a function to anything except another function.
  3. You don't actually store a value anywhere; you are only storing a function.
  4. In your example, you store two different values to the same VARIABLE_NAME . Is that intentional?

If you want to create a property map, then you need to create a storable object that can be stored into the map, and can compare its value to a provided value. For instance,

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

Now create appropriate sub-classes:

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

Your property map now looks like:

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

You can now store properties into your map and compare values against those properties.

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