- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
如果我想实现以下目标,我一直在使用 ConcurrentHashMap
。
ConcurrentModificationException
的情况下迭代 map ,而另一个线程正在修改 map 内容。有时,我使用 enum
作为键,从 EnumMap Javadoc ,我意识到,
Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.
因此,更换对我来说安全吗
Map<Country, String> map = new ConcurrentHashMap<Country, String>();
与
Map<Country, String> map = Collections.synchronizedMap(new EnumMap<Country, String>(Country.class));
我知道 EnumMap
中没有 putIfAbsent
,但目前对我来说没问题,因为我不需要它。
最佳答案
你不能这样做有两个原因:
Collections.synchronizedMap
的迭代器不同步)。Iterator
的契约(Contract)将被破坏 - 在 hasNext()
之后调用 next()
时,您可能会得到 NoSuchElementException
> 返回 true
。关于java - 用 EnumMap 替换 ConcurrentHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703882/
我有一段代码,我认为应该编译,但事实并非如此。这是代码: public class Program { public void myMethod(List> map) { } public void
有没有人有什么优越的想法,EnumMap或 Properties (或者至少在我的情况下?)我正在使用 3rd 方软件包,该软件包使用他们的方法在我的代码和他们的应用程序之间进行通信,如下所示: Th
出于个人兴趣,我正在对各种转义特殊字符的方法进行基准测试。 一位同事建议 EnumMap 也可能很快,以便检查映射中是否包含字符。 我正在尝试以下代码,它可以使用 containsValue(); 但
我最近一直在阅读 Java。所以我在下面有一个枚举,它充当带有键“JESSIE”和值“My favorite cat”的 map 。 那么为什么有人需要使用 EnumMap?谢谢 public enu
在我的代码中,我有一个枚举,其中每个值都存储一个单独的 EnumMap。但是,当我尝试使用以下代码在构造函数或初始化程序中初始化 EnumMap 时: public static void main(
我正在尝试将实例添加到以下 EnumMap: class ActiveG { EnumMap> map; .. .. } class TGData extends GData
我偶然发现 Java 中没有任何已定义方法的枚举与已定义方法的枚举之间存在奇怪的行为差异:在后一种情况下,Enum.class 和 Enum.getClass() 实际上引用了不同的编译类,即 !En
这个问题已经有答案了: What are the reasons why Map.get(Object key) is not (fully) generic (11 个回答) 已关闭 7 年前。 [
EnumMap 定义如下: Class EnumMap,V> “K extends Enum”到底是什么意思? 我可以理解这个例子: K extends Number 在这种情况下,K 是扩展 Num
这有什么区别: public enum Direction { NORTH(90), EAST(0), SOUTH(270), WEST(180); priva
我是第一次使用 EnumMap,不明白传递的参数实际上在做什么。据我所知,它只是“K.class”,其中 K 是 map 键。这工作得很好,但我在 Java 的其他任何地方都没有看到它,我不清楚它在构
我正在尝试了解如何反序列化 EnumMap。到目前为止,我一直在将 Gson 库用于其他一切,并且取得了成功。这被证明是困难的。 这是一个基本的想法: import java.lang.reflect
我尝试使用一个简单的 java EnumMap 来存储道路类型到默认速度的映射。但我立即遇到了以下问题: 我创建了一个简单的枚举,如下所示: public enum RoadCategory {
我有一个枚举和一个 EnumMap . 我将 map 放入一个类中以隐藏“字节”值。所以我有一个set(Parameter, int)和set(Parameter, boolean)方法。 publi
我遇到了由不同类加载器加载的枚举类型的奇怪行为。在公共(public)库中,我有枚举定义(类似于以下内容): enum MyEnumType { VAL_1, VAL_2, VAL_3 }; 我有第一
在 Java 中,EnumMap 具有恒定的访问时间,因为它们可以通过使用枚举的序数值作为索引的数组来实现。 如果我有一个 EnumMap 如何获取数组? 示例: enum Abc { A, B, C
我需要在 JavaFX 应用程序中初始化以下私有(private)成员,我正在尝试组织 gui 小部件,但我不知道正确的语法,有人可以让我知道正确的语法吗: 这是我用于 EnumMap 的枚举 enu
为什么我不能像这样创建一个 EnumMap: EnumMap amountMap; 我想统计并保存每种巨魔的数量。这样做的好方法是什么? 最佳答案 只需使用Integer。泛型仅适用于对象,不适用于原
有没有一种方法可以迭代 EnumMap 而不会导致每次迭代都创建新对象? entryset 的迭代器每次都返回一个新的 Entry。我能看到的唯一方法是 for(K k: map.keySet())
Map#entrySet 上的枚举并不适用于所有 Map 实现,特别是 EnumMap、IdentityHashMap,这里是来自 Josh Bloch 的 puzzler presentation
我是一名优秀的程序员,十分优秀!