Apache通用集合Bag介面


新的介面被新增到支援bagBag介面定義了一個集合,它可以計算一個物件出現在集合中的次數。 例如,如果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]