Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

java - Sorting multiple arrays simultaneously

So i am making a program that needs to handle multiple arrays. Is there any way to sort all these arrays to reflect the sorting of one array? These values are at the same index position across all three arrays and need to stay at the same index value after sorting

Example:

I have three arrays:

String[] distance = [1,3,6,7,9];
String[] name = [Joel, John, Joe, Jill, Jane]
String[] values = [1.5,2.3,5.6,7.1,6.5];

Is there any way to sort the distance array and then reflect that sorting to the other arrays. So if I sort by name and Jane becomes 0, the other values at the same positions in the other arrays will also move to 0. How could I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A better/more object oriented approach could be to have an object holding each of the 3 fields and having it sortable on whichever field you need.

public static class MyObject implements Comparable<MyObject> {

    public int distance;
    public String name;
    public float value;


    // Replace this with whichever field is needed
    @Override
    public int compareTo(MyObject o) {
        // If it's the String
        return this.name.compareTo(o.name);
        // If it's one of the values
        return this.distance - o.distance;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...