问题描述:

I'm relatively new to the programming scene and i would like you to assist me with sorting of these arrays. The idea is to display a menu item on a textArea and sort the items by name. The parralel arrays contain food items and the other one prices.

String[] items = {"Gatspy", "Coffee", "Chicken", "Mango Juice"};

double[] prices = {8.99, 23.50, 29.90, 7.50};

网友答案:

Or how about encapsulating the item name and price in a class, then have a single array of instances of this class and use a Comparator to sort them? E.g.

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() );
网友答案:

Don't use arrays in the first place, use a Map. In your case, use a TreeMap, it's sorted by its keys.

Map<String, Double> map = new TreeMap<String, Double>();
map.put("Gatspy", 8.99);
// put the other items

Now iterate over the entries:

for(Map.Entry<String, Double> entry : map.entrySet()){
    System.out.println("<option value=\"" 
                       + entry.getValue() 
                       + "\">" 
                       + entry.getKey() 
                       + "</option>");
}

Reference: Java Tutorial > Collections Trail > The Map Interface

网友答案:

You should use objects:

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;
    }
}

Then you may have an array (or a list) of Items :

private Item[] items = new Item[] {new Item("Gtaspy", 8.99), ...};

and you may sort this array using Arrays.sort() (or Collections.sort() if you use a List instead of an array).

Read the Java tutorial on Collections for more details.

相关阅读:
Top