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