为什么在Java中设置数据结构在内部使用Map? [英] Why do Set data structures in Java use Map internally?

查看:120
本文介绍了为什么在Java中设置数据结构在内部使用Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 HashSet 使用 HashMap TreeSet 使用 TreeMap LinkedHashSet 在场景后面使用 LinkedHashMap ?因为 Set 只是携带和存储密钥而不是数值,所以没有使用额外的存储空间,如不经济?

Entry 内部类 HashMap has是以下

 类条目< K,V>实现Map.Entry< K,V> {
final K key;
V值;
条目< K,V>下一个;
final int hash;
...
....
}

设置我们并不真的需要 V值变量,对吗?那么在内部使用地图对象有什么好处和主要原因?

解决方案

减少代码,减少错误,减少测试。

重用相同的代码,你只需要优化,调试和测试一次。内存开销最小 - 每个条目的另一个指针,与Key相比可以忽略不计。


I am wondering why do HashSet uses HashMap, TreeSet uses TreeMap, and LinkedHashSet uses LinkedHashMap internally behind the scene ? since Set is only carrying and storing the key but the value, so isn't using extra memory space like being not economical ?

The Entry inner class that HashMap has is the following

class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    final int hash;
    ...
    ....
}

For Set we don't really need that V value variable, correct ? So what's the benefit and main reason of using a map object internally ?

解决方案

Less code, less bugs, less testing.

By reusing the same code, you only need to optimize, debug and test it once. The memory overhead is minimal - another pointer for each entry, negligible compared to the Key.

这篇关于为什么在Java中设置数据结构在内部使用Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆