为什么Collections.frequency在转换列表上没有按预期工作?

我过去使用过Collections.frequency,它工作正常,但我现在遇到问题,因为我正在使用int []。

基本上Collections.frequency需要一个数组,但我的数据是int []的forms,所以我转换我的列表但没有得到结果。 我认为我的错误在于转换列表但不确定如何做到这一点。

这是我的问题的一个例子:

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

有什么建议么?

这有效:

 import java.util.Arrays; import java.util.Collections; import java.util.List; public class stackexample { public static void main(String[] args) { List 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

你的问题是来自这个指令Arrays.asList(data)

返回此方法的是List而不是List

这是一个正确的实现

  int[] data = new int[] { 5,0, 0, 1}; List intList = new ArrayList(); 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); 

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