本文介绍了为什么Sun Java中的HashSet实现使用HashMap作为其后盾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 看看Java 6的源代码, HashSet< E> 实际上是使用 HashMap< E,Object> ,在集合的每个条目上使用虚拟对象实例。 我认为这样会浪费4个字节(在32位机器上)的大小。 但是,它为什么还在使用?除了使维护代码更容易之外,是否有任何理由使用它? 其实,它不仅仅是 HashSet的。 Java 6中 Set 接口的所有实现都基于基础 Map 。这不是要求;这只是实施的方式。你可以通过查看 设置 。 您的主要问题是并从 Map : 将键映射到值的对象。 地图不能包含重复的键;每个键可以映射到最多一个值。 如果您可以使用现有的代码来实现您的 Set 例如,您可以从现有的代码中实现您的 Set 。 如果您选择在没有 Map 支持的情况下实现 Set ,则必须复制旨在防止重复元素的代码。啊,美味的讽刺。 也就是说,没有什么能够阻止你以不同的方式实现你的 Set p> Looking at the source of Java 6, HashSet<E> is actually implemented using HashMap<E,Object>, using dummy object instance on every entry of the Set.I think that wastes 4 byte (on 32-bit machines) for the size of the entry itself.But, why is it still used? Is there any reason to use it besides making it easier to maintain the codes? 解决方案 Actually, it's not just HashSet. All implementations of the Set interface in Java 6 are based on an underlying Map. This is not a requirement; it's just the way the implementation is. You can see for yourself by checking out the documentation for the various implementations of Set.Your main questions areI assume that code maintenance is a big motivating factor. So is preventing duplication and bloat.Set and Map are similar interfaces, in that duplicate elements are not allowed. (I think the only Set not backed by a Map is CopyOnWriteArraySet, which is an unusual Collection, because it's immutable.)Specifically:From the documentation of Set:And from Map:If you can implement your Sets using existing code, any benefit (speed, for example) you can realize from existing code accrues to your Set as well.If you choose to implement a Set without a Map backing, you have to duplicate code designed to prevent duplicate elements. Ah, the delicious irony.That said, there's nothing preventing you from implementing your Sets differently. 这篇关于为什么Sun Java中的HashSet实现使用HashMap作为其后盾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 15:26