1
public class Solution {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int l1=Integer.parseInt(br.readLine());int count=0;
        String l2=br.readLine();
        String[] a=l2.split(" ");int[] no=new int[l1];
        for (int i=0;i<l1;i++) {
            no[i]=Integer.parseInt(a[i]);
        }
        List list=Arrays.asList(no);
        Set<Integer> set=new LinkedHashSet<Integer>(list);
        ***for (int integer : set) {***
        count=Math.max(count, Collections.frequency(list, integer));
        }
    }
}

I get java.lang.ClassCastException: [I cannot be cast to java.lang.Integer at Solution.main(Solution.java:23) at the highlighted part of the code. What is the reason for this?

Keith OYS
  • 2,285
  • 5
  • 32
  • 38
  • Possible duplicate of [Arrays.asList() of an array](http://stackoverflow.com/questions/1248763/arrays-aslist-of-an-array) – Jerry Chin Nov 05 '16 at 11:20

2 Answers2

2

You are trying to initialize a set from an array of primitive integers. When you do this

List list=Arrays.asList(no);

since List is untyped, you construct a list of integer arrays; this is definitely not what you are looking for, because you need List<Integer>.

Fortunately, this is very easy to fix: change declaration of no to

Integer[] no=new Integer[l1];

and construct list as follows:

List<Integer> list = Arrays.asList(no);

Everything else should work fine.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Set<Integer> set=new LinkedHashSet<Integer>(list); produce unchecked warnings. This masks that the correct generic type of list is List<int[]>, so set contains not Integers as intended, but arrays of ints. That's what is reported by ClassCastException: int[] (referred as [I) cannot be cast to Integer.

The simplest way to fix this code is to declare no as Integer[], not int[]. In this case, Arrays.asList will return correctly-typed List<Integer>.

kgeorgiy
  • 1,477
  • 7
  • 9