Search code examples
javaarrayssortingparallel-arrays

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


Solution

  • I would go for a different approach:

    1. Create a new object:

      public class Person {
      private name;
      private cellNo;
      
      // Implement getters and setters
      }
      
    2. Create a comparator:

      public MyComparator implements Comparator<Person> {
           public int compare(Person a, Person b) { 
      
                 return a.getName().compareTo(b.getName());
           }
      }
      
    3. Call Array.sort(persons, new MyComparator()) on a Person[] persons = ... array