Created
June 1, 2020 09:32
-
-
Save Dicee/e54be66700bf4534d49d2c24b564e62a to your computer and use it in GitHub Desktop.
Answer to a StackOverflow comment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Comparator; | |
// https://stackoverflow.com/questions/62122965/how-to-resolve-raw-use-of-parameterized-class-comparable-warning/62122994#62122994 | |
public class Main { | |
interface FooInt extends Comparable<Object> { | |
int getInt(); | |
@Override | |
default int compareTo(Object that) { | |
if (that instanceof Number) return Integer.compare(getInt(), ((Number) that).intValue()); | |
if (that instanceof FooInt) return Integer.compare(getInt(), ((FooInt) that).getInt()); | |
throw new IllegalArgumentException("Unsupported type: " + that.getClass().getName()); | |
} | |
} | |
interface FooString extends Comparable<Object> { | |
String getString(); | |
@Override | |
default int compareTo(Object that) { | |
final Comparator<String> naturalOrder = Comparator.naturalOrder(); | |
if (that instanceof CharSequence) return naturalOrder.compare(getString(), ((CharSequence) that).toString()); | |
if (that instanceof FooString) return naturalOrder.compare(getString(), ((FooString) that).getString()); | |
throw new IllegalArgumentException("Unsupported type: " + that.getClass().getName()); | |
} | |
} | |
static class Bar implements FooInt { | |
@Override | |
public int getInt() { | |
return 10; | |
} | |
} | |
static class Baz implements FooInt { | |
@Override | |
public int getInt() { | |
return 12; | |
} | |
} | |
static class FooBar implements FooString { | |
@Override | |
public String getString() { | |
return "FooBar"; | |
} | |
} | |
static <T extends Comparable<Object>> T findMax(T ... items) { | |
T max = items[0]; | |
for (T item : items) | |
if (item.compareTo(max) > 0) | |
max = item; | |
return max; | |
} | |
public static void main(String[] args) { | |
findMax(new Bar(), new Baz(), new FooBar()); // throws | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment