gpt4 book ai didi

java - 将整数对象转换为原始类型时遇到问题

转载 作者:行者123 更新时间:2023-12-02 01:27:26 25 4
gpt4 key购买 nike

我正在尝试在 codewars 上完成此挑战:https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/java我将原始数组更改为数组列表,但随后我必须使用 arrayist 中的值与原始类型进行一些比较。

我尝试使用 (int) 来转换 Integer 对象,但仍然存在转换错误。当我尝试执行 (int)(arrList.get(j)).equals(current) 时,它告诉我 boolean 值无法转换为 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;
}

}

它已编译,但测试显示:class [I无法转换为class java.lang.Integer([I和java.lang.Integer位于加载程序'bootstrap'的java.base模块中)

最佳答案

Arrays.asList(elements) 并没有做你想象的那样,它返回一个包含 int[] 数组的列表,而不是数组的元素。您无法创建基元列表。如果您想使用 List,则必须首先将 int 转换为 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++;
}
}

关于java - 将整数对象转换为原始类型时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com