How to sort two arrays with respect to eachother.

arrays, java

Solution

Since the two values are so tightly coupled together I would actually write a custom class to contain the information and then sort those classes instead of playing around with raw arrays. Doing so would leave you open to many possible bugs down the line. This allows for much better control, data encapsulation and future expansion of what methods or data your class may contain.

public class MyDistance implements Comparable<MyDistance> {
    private String placename;
    private double mileage;

    public MyDistance(String placename, double milage) {
        this.placename = placename;
        this.milage = milage;
    }

    public String getPlacename() {
        return this.placename;
    }

    public double getMilage() {
        return this.milage;
    }

    @Override
    public int compareTo(MyDistance anotherDistance)
    {
        return milage.compareTo(anotherDistance.getMilage());
    }
}

If you want more flexibility in your sort then instead of having your MyDistance class implement Comparable you can write a custom `Comparator<MyDistance>` class:

public class DistanceComparator extends Comparator<MyDistance> {
    @Override
    public int compare(MyDistance dist1, MyDistance dist2) {
        return dist1.getMilage().compareTo(dist2.getMilage());
    }
}

You can use this Comparator to sort using Collections:

List<MyDistance> distanceList = getDistanceListSomehow();
Collections.sort(distanceList, new DistanceComparator());

You are not restricted to a List, I just used it for explanatory purposes. You should look at the full range of Java Collections types to best choose one that suits your purposes. As a suggestion though, the ArrayList type is easy to use and retains order like you would want.

Problem

I have 2 arrays: ``` private String[] placeName; private Double[] miles; ``` The data in them look like this: ``` placeName = {"home", "away", "here"}; miles = {111, 11, 3}; ``` The position of the values match to each other. ie home = 111 and away = 11 I need to sort these arrays together so I don't lose how they are matched by the the number- lowest to highest. What is the best way to accomplish this? Do I need to combine the arrays first?

Original source

Related problems