-4

I have to sort the following array by the items name (the second element) how do I do this? I am stuck.

    items[0] = new Product("001","Glue sticks",6,.06);
    items[1] = new Product("002","Six inch rulers",25,.59);
    items[2] = new Product("003","Paper-ream",5,6.99);
    items[3] = new Product("004","Black ink pens",15,.97);
    items[4] = new Product("005","No. 2 pencils",20,.30);
  • Let's start from a basic question: how do you compare two Product objects? How do you know which is "greater" than the other? – RealSkeptic Nov 01 '14 at 18:59

2 Answers2

1

Use a Comparator

Arrays.sort(items, new Comparator<Product>()
{
    @Override public int compare(final Product p1, Product p2)
    {
        // TODO check for null object
        return p1.getName().compareTo(p2.getName());
     }
});
ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

maybe is better you use from arraylist and arraylist.sort() method