Java泛型比较

ist*_*anp 1 java generics comparison arraylist

你如何比较两个通用类?

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;
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误:

int key1 = ( (Entry) o1 ).getKey();
                                ^
int key2 = ( (Entry) o2 ).getKey();
                                ^
incompatible types
found   : java.lang.Object
required: int
Run Code Online (Sandbox Code Playgroud)

KV将是Integer一个圆形的ArrayList实现中使用了s.是否有一种更简单的方式(或至少有一种方法)可以像我通常那样进行比较int

Pau*_*ams 5

您还需要一般性地定义比较器:

public static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
{
  return new Comparator<T> {
    public int compare(T o1, T o2) { return o1.compareTo(o2); }
  }
}
Run Code Online (Sandbox Code Playgroud)