Reputation: 35
When I used the sortAsc_byPosition function twice
public class stringArraySort {
public static String[] sortAsc_byPosition(String[] str, int charPosition) {
for(int r=0; r<str.length-1; r++) {
for(int i=r+1; i<str.length; i++) {
int j=charPosition;
while (str[r].charAt(j)==str[i].charAt(j)) {
j++;
}
if (str[r].charAt(j)>str[i].charAt(j)) {
String tmp=str[i];
str[i]=str[r];
str[r]=tmp;
}
}
}
return str;
}
public static void main(String[] args) {
String[] productID= {"Xcra-S1836", "Zkda-D3426", "Ypdu-B5654", "Akdr-Z5075", "Jhbd-K4051"};
String[] result1=sortAsc_byPosition(productID, 5);
String[] result2=sortAsc_byPosition(productID, 6);
System.out.println("Result of array sorted by character position at 5 :" + Arrays.toString(result1));
System.out.println("Result of array sorted by character position at 6 :" + Arrays.toString(result2));
}
to get the desired result, the function failed to make it.
But, when I used the function only once, it works.
public static void main(String[] args) {
String[] productID= {"Xcra-S1836", "Zkda-D3426", "Ypdu-B5654", "Akdr-Z5075", "Jhbd-K4051"};
String[] result1=sortAsc_byPosition(productID, 5);
System.out.println("Result of array sorted by character position at 5 :" + Arrays.toString(result1));
}
What is the main cause of this problem? What is the correct way to make it? Thanks for the answer...
Upvotes: 1
Views: 46
Reputation: 393781
Your sortAsc_byPosition
method accepts an array, makes changes to that array and returns the same array. This means result1 == result2
(both variables are references to the same array object).
Therefore, when you execute the method twice, the result you'll see in the end is the sort order used by the second call.
You should return a copy of the array if you want to have two different arrays having different order.
For example:
public static String[] sortAsc_byPosition(String[] str, int charPosition) {
String[] result = Arrays.copy(str,str.length);
for(int r=0; r<result.length-1; r++) {
for(int i=r+1; i<result.length; i++) {
int j=charPosition;
while (result[r].charAt(j)==result[i].charAt(j)) {
j++;
}
if (result[r].charAt(j)>result[i].charAt(j)) {
String tmp=result[i];
result[i]=result[r];
result[r]=tmp;
}
}
}
return result;
}
Upvotes: 3