可以将数组用作 HashMap 键吗?

编程入门 行业动态 更新时间:2024-10-28 17:15:59
本文介绍了可以将数组用作 HashMap 键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果 HashMap 的键是 String[] 数组:

If a HashMap's key is a String[] array:

HashMap<String[], String> pathMap;

您可以使用新创建的 String[] 数组访问地图,还是必须是相同的 String[] 对象?

Can you access the map by using a newly created String[] array, or does it have to be the same String[] object?

pathMap = new HashMap<>(new String[]{"korey", "docs"}, "/home/korey/docs"); String path = pathMap.get(new String[]{"korey", "docs"});

推荐答案

必须是同一个对象.HashMap 使用 equals() 比较键,Java 中的两个数组只有在它们是同一个对象时才相等.

It will have to be the same object. A HashMap compares keys using equals() and two arrays in Java are equal only if they are the same object.

如果您想要值相等,那么编写您自己的容器类来包装 String[] 并为 equals() 和 hashCode().在这种情况下,最好使容器不可变,因为更改对象的哈希代码会对基于哈希的容器类造成严重破坏.

If you want value equality, then write your own container class that wraps a String[] and provides the appropriate semantics for equals() and hashCode(). In this case, it would be best to make the container immutable, as changing the hash code for an object plays havoc with the hash-based container classes.

编辑

正如其他人指出的那样,List 具有您似乎想要的容器对象语义.所以你可以做这样的事情:

As others have pointed out, List<String> has the semantics you seem to want for a container object. So you could do something like this:

HashMap<List<String>, String> pathMap; pathMap.put( // unmodifiable so key cannot change hash code Collections.unmodifiableList(Arrays.asList("korey", "docs")), "/home/korey/docs" ); // later: String dir = pathMap.get(Arrays.asList("korey", "docs"));

更多推荐

可以将数组用作 HashMap 键吗?

本文发布于:2023-11-13 21:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   HashMap   键吗

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!