我有两个数组:
arrayA = {"b","c","a"}
arrayB = {"99","11","22"}
我如何将它们排序在一起,以便arrayA = {"a","b","c"}
和arrayB = {"22","99","11"}
?
使用Arrays.sort(arrayB)
. 您甚至可以提供自定义Comparator
来影响排序。
我制作了一个字母数字排序程序,请查看。
import java.util.Arrays;
import java.util.Comparator;
public class AlphanumericSorting implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstString = firstObjToCompare.toString();
String secondString = secondObjToCompare.toString();
if (secondString == null || firstString == null) {
return 0;
}
int lengthFirstStr = firstString.length();
int lengthSecondStr = secondString.length();
int index1 = 0;
int index2 = 0;
while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
char ch1 = firstString.charAt(index1);
char ch2 = secondString.charAt(index2);
char[] space1 = new char[lengthFirstStr];
char[] space2 = new char[lengthSecondStr];
int loc1 = 0;
int loc2 = 0;
do {
space1[loc1++] = ch1;
index1++;
if (index1 < lengthFirstStr) {
ch1 = firstString.charAt(index1);
} else {
break;
}
} while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
do {
space2[loc2++] = ch2;
index2++;
if (index2 < lengthSecondStr) {
ch2 = secondString.charAt(index2);
} else {
break;
}
} while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
String str1 = new String(space1);
String str2 = new String(space2);
int result;
if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
Integer firstNumberToCompare = new Integer(Integer
.parseInt(str1.trim()));
Integer secondNumberToCompare = new Integer(Integer
.parseInt(str2.trim()));
result = firstNumberToCompare.compareTo(secondNumberToCompare);
} else {
result = str1.compareTo(str2);
}
if (result != 0) {
return result;
}
}
return lengthFirstStr - lengthSecondStr;
}
public static void main(String[] args) {
String[] alphaNumericStringArray = new String[] { "NUM10071",
"NUM9999", "9997", "9998", "9996", "9996F" };
Arrays.sort(alphaNumericStringArray, new AlphanumericSorting());
for (int i = 0; i < alphaNumericStringArray.length; i++) {
System.out.println(alphaNumericStringArray[i]);
}
}
}
这是输出:
9996 9996F 9997 9998 NUM9999 NUM10071
此链接将帮助您尝试 array.sort(Arg); http://www.leepoint.net/notes-java/data/arrays/70sorting.html
您可以使用
Arrays.sort(arrayB);
输出是
C1
C2
C3
arrayB = {"22","99","11"}
Arrays.sort(arrayB);
输出:
11
22
99
如果您将使用相同的字母并且仅使用 0 到 9 之间的 1 个数字,那么您可以按照对第一个数组进行排序的方式对其进行排序。如果您打算输入更多带有更多数字的字母,则必须实现自己的自定义比较器(假设默认行为不适合您)。
书面问题的答案似乎如此明显,以至于我认为我们不理解您的真正要求。
我猜你真正要问的是如何对一个数组进行排序,并根据排序如何重新排序第一个数组来重新排序第二个数组。(您的示例选择不当来说明这一点……但实际上确实这样做了。)
假设这就是您的意思,最简单的方法是将两个数组转换为单个数组对,根据第一个字段对对进行排序,然后使用排序后的对列表重新填充原始数组。
The (possible) snag is that the total ordering of the second array is indeterminate if the sort is not stable. (Or to put it another way, if there are duplicates in arrayA
, then the relative order of the corresponding arrayB
elements cannot be predicted.) There are ways to deal with this.