新的介面被新增到支援bag
。 Bag
介面定義了一個集合,它可以計算一個物件出現在集合中的次數。 例如,如果Bag
包含{a,a,b,c}
,則getCount("a")
方法將返回2
,而uniqueSet()
返回唯一值。
以下是org.apache.commons.collections4.Bag<E>
介面的宣告 -
public interface Bag<E>
extends Collection<E>
編號 | 方法 | 描述 |
---|---|---|
1 | boolean add(E object) |
(衝突)將指定的物件到Bag 的一個副本。 |
2 | boolean add(E object, int nCopies) |
將指定物件的nCopies 副本新增到Bag 中。 |
3 | boolean containsAll(Collection<?> coll) |
(衝突)如果包包含給定集合中的所有元素,並且尊重基數,則返回true 。 |
4 | int getCount(Object object) |
返回包中當前給定物件的出現次數(基數)。 |
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 中的一組唯一元素。 |
該介面從以下介面繼承方法 -
java.util.Collection
Bag介面範例
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]