How to reverse a String array based on it's index value

I want to reverse this:

customArray = myArray;
nameArray = new String[myArray.size()];

for (int i = 0; i < myArray.size(); i++) {
     idArray[i] = myArray.get(i).getUnitID();
     nameArray[i] = myArray.get(i).getUnitName();
}

if (sortType == SORT)
    Arrays.sort(idArray, Collections.reverseOrder());
    Arrays.sort(nameArray, ...);

I know how to reverse this by using Arrays.sort(stringArray, Collections.reverseOrder()); but not by index value.

How can I reverse the order of my nameArray based on it's nameArray[i]?.. or even better, since my idArray is actually a list of unique ID's I would like to sort nameArray based on the idArray.

Answers


The only solution to your problem is to use an OOP approach. After all, Java is an OOP Language. So instead of having two arrays:

int[] unitID
String[] unitName

which you can't sort in a way that the indexes stay corresponding, write a class Unit that implements Comparable<Unit> and use one array:

Unit[] units

then

Arrays.sort(units);

will do the job.


You would need your own class:

public class Unit implements Comparable<Unit> {

    private int id;

    private String name;

    // Constructor

    // Methods

    @Override
    public int compareTo(Unit other) {
        // sorts by id
        return this.id - other.id;
        // to sort by name, use this:
        // return this.name.compareTo(other.name);
  }
}

(Update: Now reversing an array of strings and not a list of strings.)

Use Collections.reverse together with Arrays.asList to reverse the array.

Example:

public static void main(String... args) {

    String[] array = {"one", "two", "three"};

    Collections.reverse(Arrays.asList(array)); // reverses the underlying list

    System.out.println(Arrays.toString(array)); // prints [three, two, one]
}

Need Your Help

How to use the same class accross multiple threads and return a variable

vb.net multithreading loops .net-3.5

My apologies in advance if this has already been answered, but every search I have done does not come close to what I need. Also, this is all pseudo code.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.