2009-10-03 214 views
2

我需要通过过道的项目位于例如排序购物列表:
[面包] [1]
[牛奶] [2]
[谷物] [3]爪哇2D ArrayList和排序

我打算这样做ArrayList和想知道如何制作一个二维ArrayList 奖金问题:关于如何按过道数进行排序的任何想法?

回答

5

难道你没有持有你的物品+过道信息的班级吗?喜欢的东西:

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

    // constructor + getters + setters 
} 

如果你不这样做,考虑做一个 - 它绝对不是试图这些属性粘成ArrayList的另一个的ArrayList中的更好的方法。一旦你有说类,你要么需要通过自己编写的对象Comparator或使“项” Comparable

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

    public int compareTo(Item other) { 
    return this.getAisle() - other.getAisle(); 
    } 
} 

然后你要做的就是那种调用:

List<Item> items = new ArrayList<Item>(); 
... populate the list ... 
Collections.sort(items); 
+0

好吧我会研究这个 – Raptrex 2009-10-03 00:27:19

+0

我是否需要创建多个对象或者什么,因为我认为使用ArrayList的原因是因为我不知道会有多少物品 – Raptrex 2009-10-03 00:51:49

+0

您必须创建多个物品是,并将它们添加到ArrayList。 'items.add(new Item(“Bread”,1)); items.add(new Item(“Milk”,2));'等等... – ChssPly76 2009-10-03 01:01:11

0

我知道这个问题很久以前就问过了,但实际上我有同样的问题。如果您不知道列表中有多少变量,但这不是一个大数字,您可以为每个选项都实施比较器。例如

我有ArrayList<ArrayList<Object>>,并希望通过列的排序,而且我知道,嵌套列表包含的对象数目不定的我就可以实现比较每一个可能的值:

public class SecondColumnComparator implements Comparator { 

public static boolean isNumeric(String str) { 
    try { 
     Integer integer = Integer.parseInt(str); 
    } catch (NumberFormatException nfe) { 
     return false; 
    } 
    return true; 
} 

@Override 
public int compare(Object o1, Object o2) { 

    if (isNumeric(((ArrayList<String>) o1).get(1))) { 

     Integer firstInteger = Integer.parseInt(((ArrayList<String>) o1).get(1)); 
     Integer secondInteger = Integer.parseInt(((ArrayList<String>) o2).get(1)); 

     return firstInteger.compareTo(secondInteger); 

    } 
    if (((ArrayList<Object>) o1).get(1) instanceof String) { 

     String firstString = ((ArrayList<String>) o1).get(1); 
     String secondString = ((ArrayList<String>) o2).get(1); 

     return firstString.compareTo(secondString); 
    } 

    throw new Exception(); 
} 

}

并称之为是这样的:

 switch (valueSelected) { 
     case 0: 
      Collections.sort(this.listOfLists, new FirstColumnComparator()); 
      break; 
     case 1: 
      Collections.sort(this.listOfLists, new SecondColumnComparator()); 
      break; 
     case 2: 
      Collections.sort(this.listOfLists, new ThirdColumnComparator()); 
      break; 
     case 3: 
      Collections.sort(this.listOfLists, new FourthColumnComparator()); 
      break; 
     default: 

    } 

在每一个比较只是修改.get(x)其中x是collumn数由你想排序。

可能会使用boolean isNumeric(String str);函数,因为您不能在一个列表中存储不同类型的对象,所以我将这个识别放到比较器中,并将String解析为任何其他类型。

请记住,这个comparator及其“计算”被称为每一个算法的比较,所以它是非常低效的...... 尽管这样的事实,这是一种溶剂。