Array.sort未完全排序元素求助:字符串数组逆序排序异常
问题分析与解决方案
嘿,我一眼就瞅出你代码里的问题啦!你现在得到的排序结果完全不符合预期,核心原因是你在对字符串数组按字典序排序,而不是数值大小。
当你用Collections.reverseOrder()对String[]排序时,它会按照字符串的字典顺序来比较。比如"10"的第一个字符是'1',ASCII码比'4'、'5'、'8'都小,所以在倒序字典排序里,它会被排到最后,这就导致了你看到的[8, 5, 4, 10]这个奇怪结果。
下面给你两种靠谱的解决方案:
方案一:转换为整数数组后排序
先把输入的字符串数组转换成整数数组,再进行倒序排序,这样就会严格按照数值大小来排列了:
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] bankNotesValueStr = scan.nextLine().split(" "); // 转换为Integer数组 Integer[] bankNotesValue = new Integer[bankNotesValueStr.length]; for (int i = 0; i < bankNotesValueStr.length; i++) { bankNotesValue[i] = Integer.parseInt(bankNotesValueStr[i]); } // 按数值倒序排序 Arrays.sort(bankNotesValue, Collections.reverseOrder()); // 输出结果 System.out.println(Arrays.toString(bankNotesValue)); } }
方案二:使用自定义Comparator直接排序字符串数组
如果你不想额外转换数组,也可以在排序时指定一个自定义比较器,让它按照数值大小来比较字符串:
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] bankNotesValue = scan.nextLine().split(" "); // 自定义比较器,按数值倒序排列 Arrays.sort(bankNotesValue, (a, b) -> Integer.compare(Integer.parseInt(b), Integer.parseInt(a))); // 输出结果 System.out.println(Arrays.toString(bankNotesValue)); } }
这两种方案处理输入10 4 8 5时,都会输出[10, 8, 5, 4],完全符合你的预期~
内容的提问来源于stack exchange,提问作者Sahil Shanghai
相关产品推荐
相关产品推荐

