Java 2D的ArrayList和排序 [英] Java 2D ArrayList and sorting
问题描述
我要排序的过道该项目位于例如购物清单:
[面包] [1]
[牛奶] [2]
[谷物] [3]
I need to sort a shopping list by the aisle the item is located for example:
[Bread] [1]
[Milk] [2]
[Cereal] [3]
我打算与ArrayList中做到这一点,不知道如何使一个2D的ArrayList 奖金的问题:如何通过过道数量排序任何想法
I am planning to do this with ArrayList and was wondering how to make an 2D ArrayList Bonus questions: any ideas on how to sort by the aisle number?
推荐答案
你没有保存您的项目+过道信息类?是这样的:
Don't you have a class that holds your item + aisle information? Something like:
public class Item {
private String name;
private int aisle;
// constructor + getters + setters
}
如果你不这样做,考虑使一个 - 它绝对不是试图坚持这些属性为ArrayList中在另一个ArrayList的一个更好的方法。一旦你有说类,你要么需要编写的比较为对象,或进行'项目'的可比通过自身:
If you don't, consider making one - it's definitely a better approach than trying to stick those attributes into ArrayList within another ArrayList. Once you do have said class, you'll either need to write a Comparator for your objects or make 'Item' Comparable by itself:
public class Item implements Comparable<Item> {
.. same stuff as above...
public int compareTo(Item other) {
return this.getAisle() - other.getAisle();
}
}
然后你要做的就是调用排序:
Then all you do is invoke sort:
List<Item> items = new ArrayList<Item>();
... populate the list ...
Collections.sort(items);
这篇关于Java 2D的ArrayList和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!