【问题标题】:Java Generics comparisonJava 泛型比较
【发布时间】: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

KV 将在循环数组列表实现中使用 Integers。有没有一种更简单的方法(或至少一种有效的方法)可以像我通常与int 一样进行比较?

【问题讨论】:

  • Java 不知道,泛型对象将用于什么。
  • 您能否发布更多的编译错误 - 包括行号。这个问题可能没问题,但一般来说,在寻求帮助时这是有用的信息。

标签: java generics comparison arraylist


【解决方案1】:

您还需要笼统地定义比较器:

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

【讨论】:

  • 伟大的通用。保留它。
【解决方案2】:

将比较器代码更改为:

public static Comparator<Entry<Integer,?>> KeyComparator = new Comparator<Entry<Integer,?>>()
  {
     public int compare(Entry<Integer,?> o1, Entry<Integer,?> o2)
       {
         Integer key1 = o1.getKey();
         Integer key2 = o2.getKey();
         return key1.compareTo(key2);
       }
  }

这将产生强制泛型的副作用,并确保您不会将其用于未使用整数作为键的条目。

但是,您可能会发现您应该只让 getKey() 返回 Integer 而不使用泛型。保持&lt;K&gt;虽然...

【讨论】:

    【解决方案3】:

    您在 Entry 类中的密钥不是int 类型,而是K 类型。而且因为您没有对 Comparator 进行参数化,所以它默认为 Object

    如果您确定将 Integer 用于 K 和 V,那么在这种情况下您不需要泛型。在这种情况下使用Comparator&lt;Integer&gt;

    提示:在这种情况下,您可以依赖继承的 Integer#compareTo(Integer i) 方法,因为整数是可比较的(除了 java 原语,如 int

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多