gpt4 book ai didi

Java 9、Set.of() 和 Map.of() 可变参数重载

转载 作者:IT老高 更新时间:2023-10-28 20:29:15 26 4
gpt4 key购买 nike

我正在研究 Immutable 的工厂方法 Collection 品。我看到 Set.of()方法有 10 个可变参数重载(Map.of() 相同)。我真的不明白为什么会有这么多。最后函数ImmutableCollections.SetN<>(elements)无论如何都会被调用。

在文档中我发现了这个:

While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls.

困惑确实值得性能提升吗?如果是,那么理想情况下是否会为任何 N 创建一个单独的方法?元素?

最佳答案

目前无论如何都会调用该方法 - 这可能会改变。例如,它可能创建了一个 Set 只有三个元素,4 等等。

并非所有都委托(delegate)给 SetN - 具有零、一和二元素的那些具有 ImmutableCollections.Set0 的实际类, ImmutableCollections.Set1ImmutableCollections.Set2

或者你可以阅读关于这个的实际问题... here阅读该问题中来自 Stuart Marks 的评论 - 因为他是创建这些集合的人。

关于Java 9、Set.of() 和 Map.of() 可变参数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com