
- Commons Collections 教程
- Commons Collections - 首頁
- Commons Collections - 概覽
- Commons Collections - 環境設定
- Commons Collections - Bag 介面
- Commons Collections - BidiMap 介面
- Commons Collections - MapIterator 介面
- Commons Collections - OrderedMap 介面
- Commons Collections - 忽略空值
- Commons Collections - 合併與排序
- Commons Collections - 物件轉換
- Commons Collections - 物件過濾
- Commons Collections - 安全的空檢查
- Commons Collections - 包含
- Commons Collections - 交集
- Commons Collections - 差集
- Commons Collections - 並集
- Commons Collections 資源
- Commons Collections - 快速指南
- Commons Collections - 有用資源
- Commons Collections - 討論
Apache Commons Collections - Bag 介面
添加了新的介面來支援 Bag。Bag 定義了一個集合,它計算物件在集合中出現的次數。例如,如果一個 Bag 包含 {a, a, b, c},那麼 getCount("a") 將返回 2,而 uniqueSet() 將返回唯一值。
介面宣告
以下是 org.apache.commons.collections4.Bag<E> 介面的宣告:
public interface Bag<E> extends Collection<E>
方法
Bag 介面的方法如下:
序號 | 方法及描述 |
---|---|
1 | boolean add(E object) (違反)將指定物件的副本新增到 Bag 中。 |
2 | boolean add(E object, int nCopies) 將指定物件的 nCopies 個副本新增到 Bag 中。 |
3 | boolean containsAll(Collection<?> coll) (違反)如果 Bag 包含給定集合中的所有元素,則返回 true,並考慮基數。 |
4 | int getCount(Object object) 返回 Bag 中給定物件的出現次數(基數)。 |
5 | Iterator<E> iterator() 返回整個成員集的迭代器,包括由於基數造成的副本。 |
6 | boolean remove(Object object) (違反)從 Bag 中移除給定物件的所有出現。 |
7 | boolean remove(Object object, int nCopies) 從 Bag 中移除指定物件的 nCopies 個副本。 |
8 | boolean removeAll(Collection<?> coll) (違反)移除給定集合中表示的所有元素,並考慮基數。 |
9 | boolean retainAll(Collection<?> coll) (違反)移除 Bag 中不在給定集合中的任何成員,並考慮基數。 |
10 | int size() 返回 Bag 中所有型別專案的總數。 |
11 | Set<E> uniqueSet() 返回 Bag 中唯一元素的 Set。 |
繼承的方法
此介面繼承自以下介面:
- java.util.Collectio。
Bag 介面示例
BagTester.java 的示例如下:
import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.bag.HashBag; public class BagTester { public static void main(String[] args) { Bag<String> bag = new HashBag<>(); //add "a" two times to the bag. bag.add("a" , 2); //add "b" one time to the bag. bag.add("b"); //add "c" one time to the bag. bag.add("c"); //add "d" three times to the bag. bag.add("d",3 //get the count of "d" present in bag. System.out.println("d is present " + bag.getCount("d") + " times."); System.out.println("bag: " +bag); //get the set of unique values from the bag System.out.println("Unique Set: " +bag.uniqueSet()); //remove 2 occurrences of "d" from the bag bag.remove("d",2); System.out.println("2 occurences of d removed from bag: " +bag); System.out.println("d is present " + bag.getCount("d") + " times."); System.out.println("bag: " +bag); System.out.println("Unique Set: " +bag.uniqueSet()); } }
輸出
您將看到以下輸出:
d is present 3 times. bag: [2:a,1:b,1:c,3:d] Unique Set: [a, b, c, d] 2 occurences of d removed from bag: [2:a,1:b,1:c,1:d] d is present 1 times. bag: [2:a,1:b,1:c,1:d] Unique Set: [a, b, c, d]