gpt4 book ai didi

java - 如何复制 java.util.Properties 对象?

转载 作者:太空狗 更新时间:2023-10-29 22:46:16 24 4
gpt4 key购买 nike

我有以下字段和构造函数:

private final Properties properties;

public PropertiesExpander(Properties properties) {
this.properties = properties;
}

好的做法是在构造函数中复制每个可变集合。我想做一个浅的、独立的副本。我怎样才能做到这一点?

我的第一个想法是使用 putAll() 方法:

private final Properties properties = new Properties();

public PropertiesExpander(Properties properties) {
this.properties.putAll(properties);
}

有没有更简单、更高效或更惯用的方法来做到这一点?也许在 Guava 或 Apache Commons 中有一些实用程序?

最佳答案

使用 putAll()很棒......如果你需要留在Properties .它在 O(number of elements) 中运行并且开销很小。我建议的唯一区别是远离 Properties出于性能原因,除非你需要它,因为它继承自 Hashtable .另外,不要使用 Properties因为它实际上不符合任何接口(interface),只是 Dictionary这是一个抽象类;这将限制您的选择。请参阅:What does it mean to "program to an interface"?

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

无论你做什么,都不要使用 clone() , 它不安全且性能不佳。请参阅:Java: Why shouldn't clone() be used for defensive copying?


您编辑了您的问题以询问 Guava 和 apache-commons。如果它是纯粹的防御性副本,并且它是不可变的,我建议使用 Map<String, String> map = ImmutableMap.copyOf(properties) .注意:同样,这不使用实际的 Properties反对因为Hashtable除非你需要,否则不推荐。来自 the wiki

When you don't expect to modify a collection, or expect a collection to remain constant, it's a good practice to defensively copy it into an immutable collection.

Important: Each of the Guava immutable collection implementations rejects null values. We did an exhaustive study on Google's internal code base that indicated that null elements were allowed in collections about 5% of the time, and the other 95% of cases were best served by failing fast on nulls. If you need to use null values, consider using Collections.unmodifiableList and its friends on a collection implementation that permits null. More detailed suggestions can be found here.

关于java - 如何复制 java.util.Properties 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31864727/

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