2012-04-13 41 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

嘗試使用一個Integer [] – 2012-04-13 00:24:19

回答

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/

你取回的int []一個List,不int

+0

非常感謝達菲,我覺得這樣的事情是問題,因爲我無法爲轉換後的名單上圈做了。但是是否有可能將我的列表從現有格式轉換爲此?我的核心數據是在int []中,並且它將會有點難以改變輸入,所以我試圖將它轉換成一個新的列表,而不是做這個測試。 – 2012-04-13 00:28:07

+0

轉換問題已在[之前](http://stackoverflow.com/q/880581/422353)中提出,並且沒有單行解決方案。我覺得最簡單的方法就是使用'int []'來操作你自己的頻率函數。 – madth3 2012-04-13 00:39:05

+0

單獨使用JDK並沒有單行解決方案,但是Guava的['Ints.asList'](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google /common/primitives/Ints.html#asList(int ...))將在一行中完成這項工作。 – 2012-04-13 02:12:41

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 []? – 2012-04-13 00:32:34

+0

您可以隨時瀏覽您的int []並將Integer []的每個元素設置爲當前值。 – 2012-04-13 00:35:31

+0

http://stackoverflow.com/questions/880581/how-to-convert-int-to-integer-in-java – 2012-04-13 00:38:04

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); 
相關問題