2016-03-21 7 views
0

特定の数を含むArrayListの特定の要素を数えたいと思います。ArrayList内の特定の要素を数えます。

int count = 0; 
for (ArrayList a: ArrayLists) { 
    if (a.getEverything == 50) { 
     count++; 
    } 
    System.out.println("There are " + count + " people with with this age"); 

コードで問題が発生するのは、1度しかカウントされないため、50個の要素をすべてカウントする必要があるということです。私のArrayListには50個の要素が4つあります。だから私はカウントが4を返すようにしたい。これをどうすればできるの?

+0

あなたのコードは大丈夫のようです。それに50を持つ要素が複数あることは確かですか? – mendez7

+0

forループ内にa.getEverythingを印刷して、その中に50があるかどうかを調べることができます – denis

答えて

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)); 
0

はこれを試してみてください。

count = Collections.frequency(a,50);