【发布时间】:2025-11-23 01:25:02
【问题描述】:
因此,我已将哈希表读入 ArrayList 以进行排序。 我有很多数字值,后跟空格,然后是另一个数字,表示从文本文件中找到它的位置。所以我的未排序数组看起来像这样:
10 1
11 7
1 12
47 9
等等。
如果我按 Collection.sort();我的数组将如下所示:
10 1
1 7
11 12
47 9
所以它按字母顺序比较它们,而不是按数字。我想要的是忽略第二个数字并按第一个单词对列表进行排序。
public void xor(arrayObject[] array){
try{
FileWriter textWriter = new FileWriter(new File("xor.txt"));
ArrayList<String> temp = new ArrayList<>();
String tempString;
for(int i = 0; i < array.length; i++){
if(array[i] != null){
tempString ="";
int hash = hashFunction(i);
int length = String.valueOf(array[hash].value).length();
if(array[hash].foundFromA && !array[hash].foundFromB){
tempString += Integer.toString(array[hash].value);
for(int a = 0; a < 10-length; a++){
tempString += " ";
}
tempString += "1";
temp.add(tempString);
}
else if(!array[hash].foundFromA && array[hash].foundFromB){
tempString += Integer.toString(array[hash].value);
for(int a = 0; a < 10-length; a++){
tempString += " ";
}
tempString += "2";
temp.add(tempString);
}
}
}
Collections.sort(temp);
for(String s : temp){
textWriter.write(s);
textWriter.write(System.lineSeparator());
}
textWriter.close();
System.out.println("Writing xor file succesful");
}
catch(IOException e){
System.out.println("Failed to save file");
}
}
【问题讨论】:
-
我看不到代码,毫无疑问...您对我们有什么期望?
-
使用您自己的比较器或实现可比较的接口,然后在实现中执行您的排序逻辑
-
请展示您的实现,包括您自己的比较器。
-
不要将这两个值保存在同一个
String中。创建你自己的包含两个字段的类,然后让它实现Comparable。 -
它发布时没有代码,对不起
标签: java arrays sorting arraylist