Java 2D ArrayList和排序

Rap*_*rex 2 java 2d arraylist

我需要通过项目所在的过道对购物清单进行排序,例如:
[面包] [1]
[牛奶] [2]
[谷物] [3]

我打算用ArrayList做这个,并想知道如何制作2D ArrayList奖金问题:关于如何按过道号排序的任何想法?

Chs*_*y76 5

你有没有一个班级来保存你的项目+过道信息?就像是:

public class Item {
  private String name;
  private int aisle;

  // constructor + getters + setters 
}
Run Code Online (Sandbox Code Playgroud)

如果不这样做,请考虑制作一个 - 这绝对是一种比尝试将这些属性粘贴到另一个ArrayList中的ArrayList更好的方法.一旦你有了这个课程,你要么需要为你的对象写一个Comparator,要么让'Item' 可以自己比较:

public class Item implements Comparable<Item> {
  .. same stuff as above...

  public int compareTo(Item other) {
    return this.getAisle() - other.getAisle();
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你要做的就是调用sort:

List<Item> items = new ArrayList<Item>();
... populate the list ...
Collections.sort(items);
Run Code Online (Sandbox Code Playgroud)