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

MongoDB performance varies

php performance mongodb

i have a mongo collection like this:

What does this SQL statement do?

php sql

I am trying to understand this SQL statements :

Checking for a field error using Selenium Webdriver

python selenium webdriver

I've been trying to implement tests to check for field validation in forms. A check for specific field error messages was straightforward, but I've also tried a generic check to identify the parent