6

過去に Collections.frequency を使用したことがあり、問題なく動作しましたが、int[] を使用しているため問題が発生しています。

基本的に Collections.frequency には配列が必要ですが、私のデータは int[] の形式であるため、リストを変換しても結果が得られません。私の間違いはリストの変換にあると思いますが、その方法がわかりません。

これが私の問題の例です:

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class stackexample {
    public static void main(String[] args) {
        int[] data = new int[] { 5,0, 0, 1};
        int occurrences = Collections.frequency(Arrays.asList(data), 0);
        System.out.println("occurrences of zero is " + occurrences); //shows 0 but answer should be 2
    }
}

エラーはゼロではありませんが、アイテムをリストしようとすると奇妙なデータが表示されArrays.asList(data)ます。データを直接追加すると、リストを次のように変換する必要がありますcollections<?>

助言がありますか?

4

3 に答える 3

12

これは機能します:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class stackexample {
    public static void main(String[] args) {
        List<Integer> values = Arrays.asList( 5, 0, 0, 2 );
        int occurrences = Collections.frequency(values, 0);
        System.out.println("occurrences of zero is " + occurrences); //shows 0 but answer should be 2
    }
}

それArrays.asListはあなたが思っているものをあなたに与えていないからです:

http://mlangc.wordpress.com/2010/05/01/be-carefull-when-converting-java-arrays-to-lists/

ではなくListのが返ってきます。int []int

于 2012-04-13T00:25:57.447 に答える
4

あなたの問題はこの指示からArrays.asList(data)です。

このメソッドの戻り値は ではありList<int[]>ませんList<Integer>

ここで正しい実装

    int[] data = new int[] { 5,0, 0, 1};
    List<Integer> intList = new ArrayList<Integer>();
    for (int index = 0; index < data.length; index++)
    {
        intList.add(data[index]);
    }

    int occurrences = Collections.frequency(intList, 0);
    System.out.println("occurrences of zero is " + occurrences);
于 2012-04-13T00:27:40.907 に答える
1

API は を想定してObjectおり、プリミティブ型はオブジェクトではありません。これを試して:

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class stackexample {
    public static void main(String[] args) {
        Integer[] data = new Integer[] { 5,0, 0, 1};
        int occurrences = Collections.frequency(Arrays.asList(data), Integer.valueOf(5));
        System.out.println("occurrences of five is " + occurrences); 
    }
}
于 2012-04-13T00:27:01.120 に答える