我已从文件中读取数据,并从文件中取出每一行,然后将它们插入到数组中。我需要将这些字符串转换为字节并将它们写入基于磁盘的哈希文件。
我想要做的是将每个字符串都使用相同的哈希值,并将它们写入磁盘上的相同扇区。到目前为止,我所做的是根据它们的哈希值对它们进行排序,由于有1000个元素并且我的函数返回的最大哈希值是249,因此对于数组的末尾没有很好的效果。/ p>
线性探测导致很多字符串不合适,因此使用此数组写入我的扇区不会很有效。我应该怎么做呢?
以下是我到目前为止所做的代码,如果我不清楚的话:
addUser
答案 0 :(得分:1)
只需使用您自己的比较器对列表进行排序:
Collections.sort(list, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.hashCode(), o2.hashCode());
//or use your own hashcode functions here
}
}); //now list is sorted by hashcode
String[] orderedArray = list.toArray(new String[0]);
答案 1 :(得分:1)
我建议使用ArrayList
ArrayList
而不是数组。这将允许您将具有相同哈希的行放入同一内部ArrayList
。在外部ArrayList
中使用散列作为索引来查找正确的内部列表。对于初始化,请使用空ArrayList
填充外部列表(以便在填充内部列表时避免使用IndexOutOfBoundsException或NPE。)
// No need to put the lines into a list first;
// just sort them by hash as we read them
List<List<String>> orderedList = new ArrayList<>(maxHash3 + 1);
// add empty array lists to ordered list to hold the lines
for (int ix = 0; ix <= maxHash3; ix++) {
orderedList.add(new ArrayList<>());
}
while((line = bufferedReader.readLine()) != null){
// Use email as key
String key = line.substring(0,line.indexOf(','));
int index = hashFunc3(key);
// add line to inner ArrayList
orderedList.get(index).add(line);
}
以上用途:
private static final int maxHash3 = 249;
现在你可以这样做:
// to write the lines to disk you may for instance do something like this:
for (List<String> bucket : orderedList) {
for (String currentLine : bucket) {
// write currentLine to file
}
}
我们可能已经使用了ArrayList数组,但混合数组和集合并不总是运行得很好。