Java编程中的HashSet和BitSet详解

2025-05-29 0 59

Java编程中的HashSetBitSet详解

我在Apache的开发邮件列表中发现一件很有趣的事,Apache Commons包的ArrayUtils类的removeElements方法,原先使用的HashSet现在换成了BitSet

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
HashSet<Integer> toRemove = new HashSet<Integer>();

for (Map.Entry<Character, MutableInt> e : occurrences.entrySet()) {

Character v = e.getKey();

int found = 0;

for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {

found = indexOf(array, v.charValue(), found);

if (found < 0) {

break;

}

toRemove.add(found++);

}

}

return (char[]) removeAll((Object)array, extractIndices(toRemove));

新代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
BitSet toRemove = new BitSet();

for (Map.Entry<Character, MutableInt> e : occurrences.entrySet()) {

Character v = e.getKey();

int found = 0;

for (int i = 0, ct = e.getValue().intValue(); i < ct; i++) {

found = indexOf(array, v.charValue(), found);

if (found < 0) {

break;

}

toRemove.set(found++);

}

}

return (char[]) removeAll(array, toRemove);

为什么会使用BitSet代替HashSet呢?

据Apache Commons作者指出,这样代码执行时可以占用更少的内存,速度也更快。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java编程中的HashSet和BitSet详解 https://www.kuaiidc.com/118452.html

相关文章

发表评论
暂无评论