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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.