开发者

I want to sort two parallel arrays, one is of String and the other of double data types

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 parra开发者_StackOverflow中文版lel 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.


Possible approach could be the same as implemented in this math3 library: org.apache.commons.math3.util.MathArrays#sortInPlace

/**
 * Sort an array in place and perform the same reordering of entries on
 * other arrays.  This method works the same as the other
 * {@link #sortInPlace(double[], double[][]) sortInPlace} method, but
 * allows the order of the sort to be provided in the {@code dir}
 * parameter.
 *
 * @param x Array to be sorted and used as a pattern for permutation
 * of the other arrays.
 * @param dir Order direction.
 * @param yList Set of arrays whose permutations of entries will follow
 * those performed on {@code x}.
 * @throws DimensionMismatchException if any {@code y} is not the same
 * size as {@code x}.
 * @throws NullArgumentException if {@code x} or any {@code y} is null
 * @since 3.0
 */
public static void sortInPlace(double[] x,
                               final OrderDirection dir,
                               double[] ... yList)
    throws NullArgumentException, DimensionMismatchException {
    if (x == null) {
        throw new NullArgumentException();
    }

    final int len = x.length;
    final List<Pair<Double, double[]>> list
        = new ArrayList<Pair<Double, double[]>>(len);

    final int yListLen = yList.length;
    for (int i = 0; i < len; i++) {
        final double[] yValues = new double[yListLen];
        for (int j = 0; j < yListLen; j++) {
            double[] y = yList[j];
            if (y == null) {
                throw new NullArgumentException();
            }
            if (y.length != len) {
                throw new DimensionMismatchException(y.length, len);
            }
            yValues[j] = y[i];
        }
        list.add(new Pair<Double, double[]>(x[i], yValues));
    }

    final Comparator<Pair<Double, double[]>> comp
        = new Comparator<Pair<Double, double[]>>() {
        public int compare(Pair<Double, double[]> o1,
                           Pair<Double, double[]> o2) {
            int val;
            switch (dir) {
            case INCREASING:
                val = o1.getKey().compareTo(o2.getKey());
            break;
            case DECREASING:
                val = o2.getKey().compareTo(o1.getKey());
            break;
            default:
                // Should never happen.
                throw new MathInternalError();
            }
            return val;
        }
    };

    Collections.sort(list, comp);

    for (int i = 0; i < len; i++) {
        final Pair<Double, double[]> e = list.get(i);
        x[i] = e.getKey();
        final double[] yValues = e.getValue();
        for (int j = 0; j < yListLen; j++) {
            yList[j][i] = yValues[j];
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜