我想计算ArrayList中包含特定数字的某些元素。
int count = 0;
for (ArrayList a: ArrayLists) {
if (a.getEverything == 50) {
count++;
}
System.out.println("There are " + count + " people with with this age");
代码问题是它只计算一次,我希望它计算所有50个元素。在我的ArrayList中有4个元素,其中包含50个元素。所以我想要数到4.我怎么能这样做?
答案 0 :(得分:0)
您的代码似乎很好。假设您有ArrayList<Integer>
,而不是循环元素,您还可以使用Collections
来计算出现的次数:
ArrayList<Integer> arList = new ArrayList<Integer>();
arList.add(50);
arList.add(50);
arList.add(50);
arList.add(4);
arList.add(4);
System.out.println("No. of occurences of 50: "+Collections.frequency(arList, 50));
System.out.println("No. of occurences of 4: "+Collections.frequency(arList, 4));
答案 1 :(得分:0)
试试这个:
count = Collections.frequency(a,50);