当前位置: 首页 > 新闻动态 > 软件编程

Java编程中的HashSet和BitSet详解

作者:用户投稿 浏览: 发布日期:2026-01-10
[导读]:这篇文章主要介绍了Java编程中的HashSet和BitSet详解的相关资料,需要的朋友可以参考下

Java编程中的HashSet和BitSet详解

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

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)); 

新代码如下:

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作者指出,这样代码执行时可以占用更少的内存,速度也更快。

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

免责声明:转载请注明出处:http://www.sczxchw.cn/news/96026.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!