我在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作者指出,這樣代碼執行時可以占用更少的內存,速度也更快。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!