【发布时间】:2009-11-25 08:46:51
【问题描述】:
如何比较两个泛型类?
class Entry<K,V>
{
protected K key;
protected V value;
public K getKey() { return key; }
public V getValue() { return value; }
public static Comparator KeyComparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
int key1 = ( (Entry) o1 ).getKey();
int key2 = ( (Entry) o2 ).getKey();
if (key1 > key2)
{
return 1;
}
else if (key1 < key2)
{
return -1;
}
else
{
return 0;
}
}
};
}
我得到以下编译错误:
int key1 = ( (Entry) o1 ).getKey();
^
int key2 = ( (Entry) o2 ).getKey();
^
incompatible types
found : java.lang.Object
required: int
K 和 V 将在循环数组列表实现中使用 Integers。有没有一种更简单的方法(或至少一种有效的方法)可以像我通常与int 一样进行比较?
【问题讨论】:
-
Java 不知道,泛型对象将用于什么。
-
您能否发布更多的编译错误 - 包括行号。这个问题可能没问题,但一般来说,在寻求帮助时这是有用的信息。
标签: java generics comparison arraylist