【发布时间】:2019-03-26 16:12:28
【问题描述】:
我似乎找不到按“rent()”和“profit()”对列表进行排序的方法。我怎样才能做到这一点?
似乎找不到任何有用的东西。
父类:
public abstract class Zone
{
int area; //zonos plotas kv metrais
float price; //kaina uz kv metra
int jobPlaces; //darbo vietu skaicius
abstract float rent();
abstract float profit();
abstract float expenses();
abstract float totalProfit();
}
我有 3 个类(住宅、商业、工业)扩展了这个类并覆盖了它的抽象方法。
我定义列表:
static ArrayList<Zone> coll1 = new ArrayList<Zone>();
static ArrayList<Zone> coll2 = new ArrayList<Zone>();
static ArrayList<ArrayList<Zone>> superCollection = new ArrayList<ArrayList<Zone>>();
然后我随机(例如 3 个住宅区、5 个商业区、1 个工业区)填充 coll1 和 coll2 并将它们添加到 superCollection。
如何按“rent()”打印 superCollection,然后按“profit()”升序或降序对其进行排序?
编辑:
Collections.sort(superCollection, new Comparator<ArrayList<Zone>>()
{
@Override
public int compare(ArrayList<Zone> arg0, ArrayList<Zone> arg1)
{
return arg0.get(0).profit().compareTo(arg1.get(0).profit());
}
});
试过运行这个,但它仍然没有按利润排序:
zone rent profit
Residential zone: 11578.3 5534.4
Residential zone: 1963.7 2935.1
Residential zone: 4029.5 4987.2
Residential zone: 13399.6 11453.7
Residential zone: 2763.7 7212.9
Residential zone: 3961.3 3384.8
Commercial zone: 29041.3 59291.3
Commercial zone: 10483.6 42842.5
Industrial zone: 48332.3 939667.0
Industrial zone: 31563.8 1074516.2
Residential zone: 8347.1 3587.1
Commercial zone: 26177.9 47750.9
Industrial zone: 33917.8 1005413.1
Industrial zone: 25704.2 1251655.3
Industrial zone: 30268.5 1131300.0
Industrial zone: 42225.1 588861.8
Industrial zone: 32779.2 1220447.5
Industrial zone: 19686.2 863131.5
【问题讨论】:
-
嗨@Dziugas,欢迎来到stackoverflow.com。请阅读stackoverflow.com/help/how-to-ask并尝试用英文写变量,以便用户猜测其值。
-
编辑变量名,应该更容易想象我想要实现的目标,除非您仍然需要示例数据?
-
一个例子可能会有所帮助,因为 Arnaud 的问题仍然存在:您的列表列表的所需顺序是什么?每个单独排序,然后按第一个元素排序外部列表?也许是平均值?
-
您真的需要一个列表列表,还是可以将所有区域添加到一个列表中?
-
我需要对列表列表进行排序。我添加了数据样本,应该更清楚我想要实现的目标。
标签: java sorting compare comparator comparable