简体   繁体   中英

Trouble casting integer object to primitive type

I'm trying to do this challenge on codewars : https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/java I changed the original array into an arraylist, but then I have to use the values in arrayist to do some comparisons with primitive types.

I tried to cast the Integer objects using (int) but there's still casting errors. When I tried to do (int)(arrList.get(j)).equals(current), it tells me boolean can't be converted to 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;
    }

}

It compiled but the test shows : class [I cannot be cast to class java.lang.Integer ([I and java.lang.Integer are in module java.base of loader 'bootstrap')

Arrays.asList(elements) does not do what you think it does, it returns a list of containing the int[] array, not the elements of the array. You can not create a list of primitives. If you want to use List you must first convert the int to Integer .

You can get a List of Integer with

List<Integer> arrList = Arrays.stream(elements).boxed().collect(Collectors.toList());

however, you still have a bug in your program where you will skip numbers.

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++;
  }
}

One solution is to loop backwards instead

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++;
  }
}

You can replace

ArrayList arrList = new ArrayList<>(Arrays.asList(elements));

with

List<Integer> arrList = Arrays.stream(elements).boxed().collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM