Java 2D ArrayList and sorting

前端 未结 3 1458
执笔经年
执笔经年 2021-01-22 22:52

I need to sort a shopping list by the aisle the item is located for example:
[Bread] [1]
[Milk] [2]
[Cereal] [3]

I am planning to do this with ArrayList and

3条回答
  •  离开以前
    2021-01-22 23:47

    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 
    }
    

    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 {
      .. same stuff as above...
    
      public int compareTo(Item other) {
        return this.getAisle() - other.getAisle();
      }
    }
    

    Then all you do is invoke sort:

    List items = new ArrayList();
    ... populate the list ...
    Collections.sort(items);
    

提交回复
热议问题