1

在我的项目中,我在 MySet 和 MyMap 类中有特殊的实用方法 .of() 以使工作更轻松。

    public static <V> Set<V> of(V v1){
        Set<V> result = new LinkedHashSet<>();
        result.add(v1);
        return result;
    }

    public static <V> Set<V> of(V v1, V... other){
        Set<V> result = new LinkedHashSet<>();
        Collections.addAll(result, v1, other);
        return result;
    }

我想为这种方法使用固定容量。我的理由是更好的性能和内存经济性。

第一个例子:

        Set<V> result = new LinkedHashSet<>(1, 1);

第二:

        Set<V> result = new LinkedHashSet<>(other.length + 1, 1);

但据我了解,“负载因子”变量的 1f 值意味着双桶计数的限制 =(容量 * 负载因子)。在第一个示例中,它将是 1 个元素...

我尝试查找有关此问题的一些信息,但一无所获。创建固定大小的 Set 的最佳方法是什么?在我的情况下,我总是知道我需要多少元素。而且我不想成为开销,或者分配从未使用过的存储桶。

4

0 回答 0