String a = "34 9 -7 67 25";
String[] b = a.split(" ");
Arrays.sort(b);
System.out.println(Arrays.toString(b));
// 輸出: [-7, 25, 34, 67, 9] // "9" 排在最後!
Arrays.sort 預設按字典序(Unicode 碼位)比較字串,"9" > "6",故 "9" 排在 "67" 之後。
String a = "34 9 -7 67 25";
String[] b = a.split(" ");
int[] nums = new int[b.length];
for (int i = 0; i < b.length; i++) {
nums[i] = Integer.parseInt(b[i]);
}
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
// 輸出: [-7, 9, 25, 34, 67]
Arrays.sort(b, (s1, s2) -> Integer.compare(Integer.parseInt(s1), Integer.parseInt(s2)));
若資料量大、頻繁排序,建議一次性解析為數值陣列,避免重複解析開銷。