Why doesn't Collections.frequency work as expected in the converted list?

I used Collections.frequency in the past and it worked fine, but now I have problems when I use int [].

Basically Collections.frequency requires an array, but my data is in the form int [], so I am converting my list but not getting results. I think my mistake is to convert the list, but not sure how to do it.

Here is an example of my problem:

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

I don't get the error only zero, but I get strange data when I try to list the elements in Arrays.asList(data) , if I just add the data directly, it wants to convert my list to collections<?>

Any suggestions?

+6
source share
3 answers

It works:

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

This is because Arrays.asList does not give you what you think:

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

You are returning a List from int [] , not int .

+11
source

You have a problem with this Arrays.asList(data) statement.

the return of this method is List<int[]> not List<Integer> .

here is the correct implementation

  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); 
+4
source

The API expects Object , and primitive types are not objects. Try the following:

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

Source: https://habr.com/ru/post/913090/


All Articles