2016-11-05 74 views
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)); 
     } 
    } 
} 

我在代碼的突出部分得到了java.lang.ClassCastException: [I cannot be cast to java.lang.Integer at Solution.main(Solution.java:23)。這是什麼原因?java.lang.ClassCastException:[我不能轉換爲java.lang.Integer

+0

數組的[Arrays.asList()可能的重複](http://stackoverflow.com/questions/1248763/arrays-aslist-of-an-array) –

回答

2

您正試圖從原始整數數組中初始化一個集合。當你這樣做

List list=Arrays.asList(no); 

因爲List是類型化的,你構建整數數組的列表;這絕對不是你正在尋找的,因爲你需要List<Integer>

幸運的是,這是很容易解決:的no變更申報

Integer[] no=new Integer[l1]; 

,構建list如下:

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

一切應正常工作。

0

Set<Integer> set=new LinkedHashSet<Integer>(list);產生未經檢查的警告。這掩蓋了list的正確通用類型爲List<int[]>,因此set不包含按照預期的Integers,而是包含int s的數組。這就是ClassCastExceptionint[](簡稱[I)不能投射到Integer

修復此代碼的最簡單方法是聲明noInteger[]而不是int[]。在這種情況下,Arrays.asList將返回正確類型List<Integer>

相關問題