So I read from a text file, line by line, some information and I basicly save it in memory to arrays of different types (string and int). In total I have 2 arrays of String and 6 of int.
I want to sort 1 of the arrays (String) alphabetically and based on that sort the other arrays of string and ints in positions that were saved.
Text file example: B,United States,3,1,0,2,2,7
C,United Kingdom,3,1,2,0,2,1
A,Denmark,3,3,2,0,2,1
Those arrays that I mention are saved whenever I read one line in the text file. So, I have a string,string,int,int,int,int,int in the position 0 for starters and so on until the last line is read.
Ps: After I read the text file I'm not supposed to have again the text file and only work with the information saved in memory. (not working with objects)
Create a single Object
which represents a combination of the data types that you have for a single 'entry', and make it implement Comparable
for that type.
public class MyEntry implements Comparable<MyEntry> {
private String theStringToSortOn;
private String theOtherString;
private int theFirstInt;
private int theSecondInt;
// ...
public int compareTo(final MyEntry entry) {
int comparison = String.compare(this.theStringToSortOn, entry.theStringToSortOn);
if (comparison != 0) {
return comparison;
}
// Do some other rudimentary sorting based on the other fields of the class.
}
}
Then all you need to do is add these to a List
and sort
it.
If you're intent on sticking with the array based implementation however, then you'll need to give some form of way to identify which indices have changed in the array that you sort (and what they changed from and to), and then mirror those changes to the other arrays.
Without writing code for you, here's a naive implementation of how to achieve this with just arrays:
int
s, of the same length as this array.int
s (in the position which denotes the unmodified index).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.