为什么 LinkedCaseInsensitiveMap 同时使用 LinkedHashMap

我正在查看 LinkedCaseInsensitiveMap 的结构(spring framework 5.0.5.RELEASE)。我很好奇为什么 LinkedCaseInsensitiveMap 同时使用 LinkedHashMap 和 HashMap,为什么不直接使用 LinkedHashMap 呢?


private final LinkedHashMap<String, V> targetMap;


   public V get(Object key) {

      if (key instanceof String) {

         return this.targetMap.get(convertKey((String) key));

      }

      return null;

   }


眼眸繁星
浏览 203回答 1
1回答

慕容3067478

private final LinkedHashMap<String, V> targetMap;private final HashMap<String, String> caseInsensitiveKeys;在这种情况下targetMap,包含到您的对象的真实大小写字符串,并caseInsensitiveKeys包含将您的小写键映射到您的真实大小写键。它允许在您进行 for-each 迭代时向您显示实际大小写键,但同时它允许您不区分大小写。所以说,下面的代码:LinkedCaseInsensitiveMap<Object> map = new LinkedCaseInsensitiveMap<>();map.put("MyCustomObject", new Object());将放入"MyCustomObject" -> new Object(),targetMap并"mycustomobject" -> "MyCustomObject"放入caseInsensitiveKeys. 现在,如果您尝试打印您的所有对象,map它将在您添加而不是更改键时打印它。没有第二张地图就无法存档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java