0

I have a class called ArraySort which is generically typed

public class ArraySort<E> {
    public void bubbleSort(E[] data) {...}
}

which takes in a type when initiating it

ArraySort<Integer> ArraySort = new ArraySort<Integer>();

This class supports different sorting algorithms as such, but whenever an array is inputted with null values in it

int[] arr = {3, 1, 5, null};
ArraySort.bubbleSort(arr);

My code errors out with a null pointer exception. I already tried to use a method from this thread, but this didn't work due to a 'java.lang.ArrayStoreException'.

public E[] clean(E[] v) {
    ArrayList<E> list = new ArrayList<E>(Arrays.asList(v));
    list.removeAll(Collections.singleton(null));
    return (E[]) list.toArray(new String[list.size()]);
}

So my question is how do I remove all null values from a generically typed Array?

Community
  • 1
  • 1
Tyler Chong
  • 650
  • 2
  • 12
  • 24
  • 1
    If you follow the options in the duplicate link, you won't have to remove the `null` values, thereby affecting the state of your data, when you sort. Instead, just tell Java how to handle those nulls while sorting. – Tim Biegeleisen Jan 27 '17 at 04:34
  • Thanks! Your solution worked perfectly <3 – Tyler Chong Jan 27 '17 at 04:37

0 Answers0