且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java编程中的HashSet和BitSet

更新时间:2022-08-14 20:56:02

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


  1. HashSet toRemove = new HashSet();  
  2. for (Map.Entry e : occurrences.entrySet()) {  
  3.     Character v = e.getKey();  
  4.     int found = 0;  
  5.     for (int i = 0, ct = e.getValue().intValue(); i 
  6.         found = indexOf(array, v.charValue(), found);  
  7.         if (found 0) {  
  8.             break;  
  9.         }  
  10.         toRemove.add(found++);  
  11.     }  
  12. }  
  13.   
  14.   
  15. return (char[]) removeAll((Object)array, extractIndices(toRemove));  

作者:chszs,转载需注明。作者博客主页:http://blog.csdn.net/chszs

新代码如下:



  1. BitSet toRemove = new BitSet();  
  2. for (Map.Entry e : occurrences.entrySet()) {  
  3.     Character v = e.getKey();  
  4.     int found = 0;  
  5.     for (int i = 0, ct = e.getValue().intValue(); i 
  6.         found = indexOf(array, v.charValue(), found);  
  7.         if (found 0) {  
  8.             break;  
  9.         }  
  10.         toRemove.set(found++);  
  11.     }  
  12. }  
  13. return (char[]) removeAll(array, toRemove);  

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


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