做作业,我被困住了。

假设我有一个数组颜色:

["blue", "orange", "green", "black", "red" ]


这些颜色出现在文本中。发生颜色时,会有另一个数组将行号存储在另一个数组(位置数组)中。

[17,4,5,8,8]

现在我想通过升序出现来打印,所以输出将是:

orange
green
black
red
blue


我使用Arrays.sort()对位置数组进行排序。
我认为应该使用职位来完成。

例如,对于打印橙色,排序后的数组与颜色在数组颜色上的位置有关。

你能指出我的方向吗?

当我开始学习Java时,这是最简单的方法。

最佳答案

您需要将索引彼此关联。我建议您在一个类中进行操作(也许是一个具有属性PairString colorint line类)。

class Pair {
    public String color;
    public int line;
    public Pair(String color, int line) {
        this.color = color;
        this.line  = line;
    }
}

建立配对对象的数组(或List<Pair>)。

String[] colors = new String[] {"blue", "orange", "green", "black", "red"};
int[] lines     = new int[]    {    17,        4,       5,       8,     8};

List<Pair> pairs = new LinkedList<Pair>();
for (int i = 0; i < colors.length; i++)
    pairs.add(new Pair(colors[i], lines[i]));

根据您的Pair属性,使用Comparator(或Arrays.sort)方法用Collection.sortline数组进行排序。

Collections.sort(pairs, new Comparator<Pair>() {
    public int compare(Pair p1, Pair p2) {
        return Integer.valueOf(p2.line).compareTo(p1.line);
    }
});


另一种选择是在Comparable<Pair>中实现Pair
使用循环打印数组

关于java - Java根据位置打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7689217/

10-17 01:39