[英]Trouble casting integer object to primitive type
我正在嘗試在codewars上進行此挑戰: https ://www.codewars.com/kata/554ca54ffa7d91b236000023/train/java我將原始數組更改為arraylist,但是隨后我必須使用arrayist中的值來做一些操作與原始類型的比較。
我嘗試使用(int)強制轉換Integer對象,但仍然存在強制錯誤。 當我嘗試執行(int)(arrList.get(j))。equals(current)時,它告訴我布爾值無法轉換為int。
import java.util.*;
public class EnoughIsEnough {
public static int[] deleteNth(int[] elements, int maxOccurrences) {
ArrayList arrList = new ArrayList<>(Arrays.asList(elements));
for (int i = 0; i < arrList.size(); i++) {
int current = (int)arrList.get(i);
int occurrences = 1;
for (int j = i + 1; j < arrList.size(); j++) {
if (arrList.get(j).equals(current) && occurrences >= maxOccurrences) {
arrList.remove(j);
} else if (arrList.get(j).equals(current)) {
occurrences++;
}
}
}
int arr[] = new int[arrList.size()];
for (int i = 0; i < arrList.size(); i++) {
arr[i] = (int) arrList.get(i);
}
return arr;
}
}
它已編譯,但測試顯示:類[無法將其強制轉換為類java.lang.Integer([和java.lang.Integer在加載程序'bootstrap'的模塊java.base中)
Arrays.asList(elements)
並沒有您認為的那樣,它返回一個包含int []數組而不是數組元素的列表。 您無法創建基元列表。 如果要使用List,則必須首先將int
轉換為Integer
。
您可以使用獲取Integer
列表
List<Integer> arrList = Arrays.stream(elements).boxed().collect(Collectors.toList());
但是,您的程序中仍然存在一個錯誤,您將跳過數字。
for (int j = i + 1; j < arrList.size(); j++) {
if (arrList.get(j).equals(current) && occurrences >= maxOccurrences) {
arrList.remove(j); // This shortens the list causing us to skip the next element
j--; // One hackish way is to go back one step
} else if (arrList.get(j).equals(current)) {
occurrences++;
}
}
一種解決方案是改為向后循環
for (int j = arrList.size() - 1; j > i; j--) {
if (arrList.get(j).equals(current) && occurrences >= maxOccurrences) {
arrList.remove(j);
} else if (arrList.get(j).equals(current)) {
occurrences++;
}
}
您可以更換
ArrayList arrList = new ArrayList<>(Arrays.asList(elements));
同
List<Integer> arrList = Arrays.stream(elements).boxed().collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.