1

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.

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Can you give me an example of that in code form?
@МởṇṏсĺḕMᾶṇ Have a look here: mkyong.com/java/…
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.