Collections.frequency用法实例

Collections.frequency(Collection Object o):返回指定集合中指定对象出现的次数

 

下面以计算一堆糖果中有各颜色多少为例:

 

public class Candy {
 
 private String colar;
 
 private int weight;

 

 public String getColar() {
  return colar;
 }

 public void setColar(String colar) {
  this.colar = colar;
 }

 public int getWeight() {
  return weight;
 }

 public void setWeight(int weight) {
  this.weight = weight;
 }


 public boolean equals(Object obj) {
  Candy c = (Candy) obj;
  if(this.colar.equals(c.getColar())){
   return true;
  }
  return false;
 }
 

}

 

public class CountCandyColorList {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  Candy c = new Candy();
  c.setColar("red");
  c.setWeight(1);
  
  Candy c1 = new Candy();
  c1.setColar("red");
  c1.setWeight(2);
  
  Candy c2 = new Candy();
  c2.setColar("green");
  c2.setWeight(1);
  
  Candy c3 = new Candy();
  c3.setColar("red");
  c3.setWeight(1);
  
  List list = new ArrayList();
  list.add(c);
  list.add(c1);
  list.add(c2);
  list.add(c3);
  
  System.out.println("red ="+Collections.frequency(list, c));
  System.out.println();
  

 }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值