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