0

我有一个 Integer[]s 文件太大而无法放入内存。我想搜索所有最后一个成员 x 的数组并在其他代码中使用它们。有没有办法使用 Guava 的多重映射来做到这一点,其中 x 是键并存储在内存中,而 Integer[] 是值并存储在磁盘上?在这种情况下,键不是唯一的,但键值对是唯一的。读取这个多图(假设它是可能的)将是并发的。我也愿意接受其他方法来解决这个问题的建议。
谢谢

4

1 回答 1

3

您可以创建一个表示磁盘上的数组的类(基于它在数组文件中的索引),让我们称之为它FileBackedIntArray,并将其实例作为 a 的值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值)吗?正如您在评论中所说,您实际上并不需要s Integer[],因此在任何地方使用intss 将避免装箱/拆箱,并且会节省大量空间,因为您似乎有很多空间。希望最后一个元素 (x) 没有大量可能的值。

然后,您为每个数组创建一个实例并读取最后一个元素以将其放置在Multimap不保留数组的情况下。填充Multimap需要是顺序的,或者如果并发,则使用锁保护,但读取可以是并发的,没有任何保护。您甚至可以在填充ImmutableMultimap后创建一个HashMultimap,以防止任何修改,这是并发环境中的安全实践。

于 2012-10-01T07:59:14.003 回答