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
287 views
in Technique[技术] by (71.8m points)

java - Sort a parallel array using Arrays.sort()

Is it possible to sort an array using Arrays.sort() and thereafter have another related array positioned the same as the sorted array for example:

    String arrNames[] = new String[5];
    String arrCellNo[] = new String[arrNames.length];


    String arrNamesSorted[] = new String[arrNames.length];
    System.arraycopy(arrNames, 0, arrNamesSorted, 0, arrNames.length);
    Arrays.sort(arrNamesSorted);

From this point what i would like to do is sort the CellNo array such that if "person" had a cellNo "x", he will have the same "cellNo" "x" after the array arrNames is sorted

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can't have Arrays.sort manipulate a second array the way it's sorting the first array.

The solution is to sort your own objects that contain all the data you need. Create a Contact class with name and cell number attributes. Then create a class that implements Comparator<Contact> (say, ContactComparator) to compare the names.

Then you will be able to sort an array of Contact objects with a particular overload of Arrays.sort.

Arrays.sort(arrContacts, new ContactComparator());

All data will remain organized, in that the same name will still have the same cell number.


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

...