Java - Ordering of numbers in an array and keep that order for an array of strings

时间:2017-04-10 03:21:47

标签: java arrays sorting numbers

Java Question: I have an array of doubles and an array of strings each 26 in length. I would like the array of doubles (lets call it weights) to when going through the Arrays.sort() function, the strings get sorted in the same manner.
Example:
Before:
Name: Bob | Weight: 3.6
Name: Steve | Weight: 11.0
Name: Thomas | Weight: 2.2

After:
Name: Thomas | Weight: 2.2
Name: Bob | Weight: 3.6
Name: Steve | Weight: 11.0

I have thought about this for some time but I have no Idea how I would go about doing this.

2 个答案:

答案 0 :(得分:2)

Create a class (for example, Person). Implement Comparable<Person>. Give it two fields, name and weight. Populate an array of Person, and then call Arrays.sort. Starting with Person, that might look something like

class Person implements Comparable<Person> {
    public Person(String name, double weight) {
        this.name = name;
        this.weight = weight;
    }

    private String name;
    private double weight;

    @Override
    public int compareTo(Person o) {
        int r = Double.compare(this.weight, o.weight);
        if (r != 0) {
            return r;
        }
        return this.name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return String.format("Name: %s | Weight: %.1f", name, weight);
    }
}

And then you can print it (because it overrides toString()) like

public static void main(String[] args) {
    Person[] people = { new Person("Bob", 3.6), //
            new Person("Steve", 11.0), new Person("Thomas", 2.2) };
    System.out.println("Before Sorting");
    for (Person p : people) {
        System.out.println(p);
    }
    Arrays.sort(people);
    System.out.println("After Sorting");
    for (Person p : people) {
        System.out.println(p);
    }
}

Which outputs (as requested)

Before Sorting
Name: Bob | Weight: 3.6
Name: Steve | Weight: 11.0
Name: Thomas | Weight: 2.2
After Sorting
Name: Thomas | Weight: 2.2
Name: Bob | Weight: 3.6
Name: Steve | Weight: 11.0

答案 1 :(得分:0)

Make a class that contains a string and a double, then have an array of those, and sort them based on the doubles.