代码之家  ›  专栏  ›  技术社区  ›  Paul Croarkin

无警告通用接口的比较器

  •  1
  • Paul Croarkin  · 技术社区  · 15 年前

    鉴于:

    public interface PrimaryKey<Key extends Comparable> {
        Key getKey();
    }
    

    public class PrimaryKeyComparator implements Comparator<PrimaryKey> {
        public int compare(PrimaryKey first, PrimaryKey second) {
            return first.getKey().compareTo(second.getKey());
        }
    }
    

    这种组合可以工作,但会发出有关原始类型的警告。我尝试过各种添加类型参数的方法,但是我尝试过的每个组合都会破坏代码。

    1 回复  |  直到 15 年前
        1
  •  3
  •   bruno conde    15 年前

    试试这个:

    public interface PrimaryKey<TKey extends Comparable<TKey>> {
        TKey getId();
    }
    
    public class PrimaryKeyComparator<TKey extends Comparable<TKey>> 
                                     implements Comparator<PrimaryKey<TKey>> {
        public int compare(PrimaryKey<TKey> first, PrimaryKey<TKey> second) {
            return first.getId().compareTo(second.getId());
        }
    }