tags:

views:

1028

answers:

2

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 was wondering how to make an 2D ArrayList Bonus questions: any ideas on how to sort by the aisle number?

+3  A: 

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<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);
ChssPly76
alright I will look into this
Raptrex
would I have to make multiple objects or something, because the reason I thought of using an ArrayList was because I do not know how many items there would be
Raptrex
You'll have to create multiple Item instances, yes, and add them to ArrayList. `items.add(new Item("Bread", 1)); items.add(new Item("Milk", 2));`, etc...
ChssPly76
A: 

If you want to sort an ArrayList of ArrayLists then you can use the ColumnComparator.

If you want to sort an ArrayList of your custom Object then you can use the BeanComparator.

camickr