我有一个 Integer[] 文件,太大而无法放入内存。我想搜索包含 x 最后一个成员的所有数组,并在其他代码中使用它们。有没有办法使用 Guava 的 multimap 来做到这一点,其中 x 是键并存储在内存中,Integer[] 是值并存储在磁盘上?在这种情况下,键不是唯一的,但键值对是唯一的。对该多重映射的读取(假设可能)将是并发的。我也愿意接受其他解决此问题的方法的建议。
谢谢
最佳答案
您可以创建一个表示磁盘上数组的类(基于其在数组文件中的索引),我们将其称为 FileBackedIntArray
,并将其实例作为 HashMultimap<Integer, FileBackedIntArray>
的值:
public class FileBackedIntArray {
// Index of the array in the file of arrays
private final int index;
private final int lastElement;
public FileBackedIntArray(int index, int lastElement) {
this.index = index;
this.lastElement = lastElement;
}
public int getIndex() {
return index;
}
public int[] readArray() {
// Read the file and deserialize the array at the associated index
return smth;
}
public int getLastElement() {
return lastElement;
}
@Override
public int hashCode() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o == null || o.getClass() != getClass()) {
return false;
}
return index == ((FileBackedIntArray) o).index;
}
}
您真的需要Integer[]
吗?而不是int[]
,顺便说一句(即您可以拥有 null
值)? 正如您在评论中所说,您实际上并不需要 Integer[]
,所以使用 ints
到处都是 s 将避免装箱/拆箱,并且会节省大量空间,因为您似乎有很多它们。希望最后一个元素 (x) 没有大量可能的值。
然后,您为每个数组创建一个实例并读取最后一个元素以将其放入 Multimap
而不保留阵列。填充Multimap
如果并发,则需要是顺序的或用锁保护,但读取可以是并发的,没有任何保护。您甚至可以创建一个 ImmutableMultimap
一旦HashMultimap
已填充,以防止任何修改,这是并发环境中的安全做法。
关于java - 使用随机访问文件的 Guava multimap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12668924/