2012-04-13 1 views
6

私は過去にCollections.frequencyを使用していましたが、うまくいきましたが、私はint []を使用しているので問題があります。変換されたリストでCollections.frequencyが期待どおりに機能しないのはなぜですか?

基本的に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<?>に変換したい

どのような提案がありますか?

+0

整数[] –

答えて

11

これは動作します:

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/

あなたはintint []Listではなくバック取得しています。

+0

本当にありがとうございましたダフィーを使用してみてください、私は私が変換されたリスト上のループのために行うことができなかったので、このような何かが問題だと思いました。しかし、私のリストを既存のフォーマットからこれに変換することは可能ですか?私のコアデータはint []であり、入力を変更するのは少し難しいので、このテストを行う代わりに新しいリストに変換しようとしていました。 –

+0

変換の質問は[以前](http://stackoverflow.com/q/880581/422353)とされており、1行の解決策はありません。私はこれの中で最も簡単な方法は 'int []'で動作する独自の周波数関数を使うことです。 – madth3

+0

JDKだけでは1行のソリューションはありませんが、Guavaの['Ints.asList'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google /common/primitives/Ints.html#asList(int ...))は1行でジョブを実行します。 –

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

私はそれをint []に変換してint []をInteger []に変換していますか? –

+0

あなたはいつもあなたのint []を歩き、Integer []の各要素を現在の値に設定することができます。 –

+0

http://stackoverflow.com/questions/880581/how-to-convert-int-to-int-integer-in-java –

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); 
関連する問題