按对象变量对Arraylist进行排序

时间:2013-07-20 05:04:17

标签: sorting arraylist

有关如何应用Collections.sort方法按itemData ArrayList中每个grocItem对象的优先级对我的arraylist进行排序的任何想法?

public class GroceryProgram {

    private final static int GROC_SIZE = 6;
    private final List<ItemData> itemData = new ArrayList<ItemData>();

    private void setUpList() {

        Scanner keyboard = new Scanner(System.in);

        for (int i = 0; i < GROC_SIZE; i++)  {

           System.out.print("\nEnter item name (" + i + ") : ");               
           String name = keyboard.next();

           System.out.print("\nEnter the price of item (" + i + ") : ");
           double cost = keyboard.nextDouble();

           System.out.print("\nEnter Priority Number (" + i + ") : ");
           int priority = keyboard.nextInt();

           ItemData grocItem = new ItemData(name, cost, priority);
           itemData.add(grocItem); // add grocery items to itemData ArrayList

           Collections.sort(grocItem);
           for (Int priority : priority) {
               System.out.println(integer);

3 个答案:

答案 0 :(得分:2)

使用比较器调用sort()。例如,优先级升序的比较器可能如下所示。

Collections.sort( items, new Comparator<ItemData>() {
    public int compare (ItemData o1, ItemData o2) {
        int comp = o1.getPriority() - o2.getPriority();
        return comp;
    }
});

PS:'itemData'是错误的变量命名 - 它将引用单个项目,而不是列表。 'groceryItems','stockItems'或'itemList'会更好。

变量名称可让您以有意义,清晰,简洁的英语说出您的软件。

希望这有帮助。

答案 1 :(得分:0)

你可以使用Collections.sort(List list, Comparator c)来解决这个问题吗?您可以简单地执行以下操作:

Collections.sort(itemData, new Comparator() {
  public int compare(Object o1, Object o2) {
    // Return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
  }
}

答案 2 :(得分:0)

您可以使用自定义比较器,如下所示:

Collections.sort(itemData ,new PriorityComparator());

        //print sorted arraylist,it will print the data in ascending order (low priority->high priority).feel free to modify if you want to go for descending order
        System.out.println(itemData );

PriorityComparator类定义:

private static class PriorityComparator implements Comparator{

    @Override
    public int compare(ItemData object1, ItemData object2) {
        return (object1.priority< object2.priority) ? -1: (object1.priority> object2.priority) ? 1:0 ;
    }

}

参考:

how-to-sort-arraylist-in-java-example

我希望它会有所帮助!!