检查比较器是否接受对象
Check if comparator accepts object
在SortedMap doc中我们有如下句子:
All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator)
如何检查指定比较器是否接受密钥(也是通用类型)?
再者,如果key是被comparator接受的,按定义不是comparable吗?
代码:
Comparator<KeyType> c = null; // not nesc. specified in constructor.
public int comparePlz(KeyType k1, KeyType k2) {
if (c != null)
return c.compare(k1, k2);
// if c is null, doc stipulates KeyType implements Comparable.
// However as expected this gives compiler error. But typecasting would
// be unsafe.
return k1.compareTo(k2);
}
当然我可以只添加 KeyType extends Comparable<? super KeyType>
但想知道是否有没有办法做到这一点。
我也无法向构造函数添加任何参数。
我最终直接从
TreeMap implementation.
在SortedMap doc中我们有如下句子:
All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator)
如何检查指定比较器是否接受密钥(也是通用类型)?
再者,如果key是被comparator接受的,按定义不是comparable吗?
代码:
Comparator<KeyType> c = null; // not nesc. specified in constructor.
public int comparePlz(KeyType k1, KeyType k2) {
if (c != null)
return c.compare(k1, k2);
// if c is null, doc stipulates KeyType implements Comparable.
// However as expected this gives compiler error. But typecasting would
// be unsafe.
return k1.compareTo(k2);
}
当然我可以只添加 KeyType extends Comparable<? super KeyType>
但想知道是否有没有办法做到这一点。
我也无法向构造函数添加任何参数。
我最终直接从 TreeMap implementation.