目录

Commons Collections - Bag

新的界面被添加到支持袋。 Bag定义了一个集合,用于计算对象在集合中出现的次数。 例如,如果Bag包含{a,a,b,c},则getCount(“a”)将返回2,而uniqueSet()将返回唯一值。

接口声明 (Interface Declaration)

以下是org.apache.commons.collections4.Bag 界面的声明 -

public interface Bag<E>
   extends Collection<E>

方法 (Methods)

Sr.No. 方法和描述
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)

(违规)从包中删除所有出现的给定对象。

7

boolean remove(Object object, int nCopies)

从Bag中删除指定对象的nCopies副本。

8

boolean removeAll(Collection《?》 coll)

(违规)删除给定集合中表示的所有元素,尊重基数。

9

boolean retainAll(Collection《?》 coll)

(违规)根据基数删除不在给定集合中的任何行李成员。

10

int size()

返回所有类型的包中的项目总数。

11

Set《E》 uniqueSet()

返回Bag中的一组唯一元素。

方法继承 (Methods Inherited)

此接口从以下接口继承方法 -

  • java.util.Collection

袋接口示例

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());
   }
}

输出 (Output)

它将打印以下结果。

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]
↑回到顶部↑
WIKI教程 @2018