我想对两个并行数组进行排序,一个数组为String,另一个数组为double数据类型

问题描述

|| 我是编程领域的新手,我希望您能协助我对这些数组进行排序。想法是在textArea上显示一个菜单项,然后按名称对这些项进行排序。平行排列包含食品和其他价格。
String[] items  = {\"Gatspy\",\"Coffee\",\"Chicken\",\"Mango Juice\"};
double[] prices = {8.99,23.50,29.90,7.50};
    

解决方法

还是将商品名称和价格封装在一个类中,然后具有该类的单个实例数组并使用ѭ1进行排序,该怎么办? 例如。
public class Item {
private String name;
private double price;
...
//getters and setters for name and price
}

...

Item []items = { new Item(\"Gatspy\",8.99),.... };

...

class ItemComparator implements Comparator {
 public int compare( Object o1,Object o2 ) {
  Item i1 = (Item)o1;
  Item i2 = (Item)o2;
  return i1.getName().compareTo(i2.getName());
 }
}

...

Arrays.sort( items,new ItemComparator() );
    ,首先不要使用数组,请使用
Map
。在您的情况下,请使用
TreeMap
,并按其键排序。
Map<String,Double> map = new TreeMap<String,Double>();
map.put(\"Gatspy\",8.99);
// put the other items
现在遍历条目:
for(Map.Entry<String,Double> entry : map.entrySet()){
    System.out.println(\"<option value=\\\"\" 
                       + entry.getValue() 
                       + \"\\\">\" 
                       + entry.getKey() 
                       + \"</option>\");
}
参考:Java教程> Collections Trail> Map接口     ,您应该使用对象:
public class Item {
    private String name;
    private double price; // you shouldn\'t use doubles for money,but this is unrelated

    public Item(String name,double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return this.name;
    }

    public double getPrice() {
        return this.price;
    }
}
然后,您可能会有一个Items数组(或列表):
private Item[] items = new Item[] {new Item(\"Gtaspy\",...};
并且您可以使用Arrays.sort()对该数组进行排序(如果使用List而不是数组,则可以使用Collections.sort())。 阅读Collections上的Java教程以获取更多详细信息。