首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Collections.frequency用法范例

2014-01-09 
Collections.frequency用法实例Collections.frequency(Collection Object o):返回指定集合中指定对象出现

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

?}


}

热点排行