为什么Collections.frequency在转换列表上没有按预期工作? [英] Why is Collections.frequency not working as expected on converted list?
问题描述
我过去使用过Collections.frequency并且工作正常,但我现在遇到问题,因为我正在使用int []。
I have used Collections.frequency in the past and its worked fine but I'm having problems now that I'm using an int[].
基本上是收藏.frequency需要一个数组,但我的数据是int []的形式,所以我转换我的列表,但没有得到结果。我认为我的错误在于转换列表但不确定如何操作。
Basically Collections.frequency requires a array but my data is in the form of a int[] so I convert my list but am not getting an results. I think my mistake is in the converting of the list but not sure how to do it.
以下是我的问题示例:
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)
中的项目时,我得到了奇怪的数据,如果我只是直接添加数据,它想要将我的列表转换为集合<?>
I don't get an error just zero but I get weird data when I try to list the items in Arrays.asList(data)
, if I just add data directly, it wants to convert my list into collections<?>
有任何建议吗?
推荐答案
这有效:
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
没有给出你的想法:
It's because Arrays.asList
isn't giving you what you think it is:
http://mlangc.wordpress.com/2010/05/ 01 / be-carefull-when-converting-java-arrays-to-lists /
您将获得列表
int []
,而非 int
。
这篇关于为什么Collections.frequency在转换列表上没有按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!