简体   繁体   English

对ArrayLists的通用ArrayList进行排序

[英]Sorting a generic ArrayList of ArrayLists

I have a list of points. 我有一个点列表。 I represented this as an ArrayList of ArrayLists. 我将其表示为ArrayLists的ArrayList。 I'm trying to use generics so that the list can store Integers, Floats, etc. and treat them the same. 我正在尝试使用泛型,以便列表可以存储整数,浮点数等,并对它们进行相同处理。 So I have: 所以我有:

ArrayList<ArrayList<? extends Number>>. 

I need to compare these lists based on one element in each inner list. 我需要根据每个内部列表中的一个元素来比较这些列表。

So to do that I wrote a custom Comparator that I'm using in Collections.sort 所以为了做到这一点,我写了一个我在Collections.sort中使用的自定义Comparator

The Comparator looks like: 比较器看起来像:

int compare(ArrayList<? extends Number> a, ArrayList<? extends Number> b )
{
    return a.get(index).compareTo(b.get(index))
}

This doesn't compile of course. 当然这不编译。 The compiler complains that there is no compareTo method for the wildcard class. 编译器抱怨通配符类没有compareTo方法。

Is what I'm trying to do even possible? 我正在努力做甚么可能吗?

How about defining your Comparator class as: 如何将Comparator类定义为:

class MyComparator<T extends Number & Comparable<T>> 
                                          implements Comparator<ArrayList<T>> {
    @Override
    public int compare(ArrayList<T> a, ArrayList<T> b) {
        return a.get(index).compareTo(b.get(index));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM