Reputation: 3357
I am using Arrays.Sort() function in java to sort a names in 2D array storing names and corresponding numbers. I want number to remain in the same indices as to the corresponding names. How do I do it?
Thanks in advance.
CODE
String[][] contact = new String[3][3];
contact[0][0] = "b";
contact[0][1] = "c";
contact[0][2] = "a";
contact[1][0] = "2";
contact[1][1] = "3";
contact[1][2] = "1";
Arrays.sort(contact[0]);
Example:
b c a
2 3 1
OUTPUT:
a b c
2 3 1
I want to get:
a b c
1 2 3
Upvotes: 0
Views: 119
Reputation: 15497
Before you sort your array make a copy of it, then after sorting loop through the sorted one and use originalArray.indexOf(newArray[i])
to get the original index of the string, then set the new "index array"[i] to the value of the original index array[original index of the string].
You need to turn the original array into a list before you do this with Arrays.asList(originalArray)
.
Upvotes: 2
Reputation: 1900
public class MatrixCell{
private Integer x = 0;
private Integer y = 0;
private String name = "";
public MatrixCell(int x, int y, String name){
this.x = x;
this.y = y;
this.name = name;
}
//getters and setters
}
Then make an array of MatrixCell and done. Although this way you have to make too the sort algorithm.
Upvotes: 0