Search code examples
javagenericswrapperprimitive

Unchecked cast warning when wrapping primitives for generic array


I'm writing a small package of sorting functions that work on an object of class SortableArray<T extends Comparable<T>> because I want to be able to sort primitive objects like int, I need to wrap the primitives in a class object, in this case specifically, Integer. So, I overloaded my constructor to take an array of type int, wrap each in an Integer, store it in an array, temp, and then point GenList to temp. I added a cast of (T[]) to make the IDE happy, but now I have an unchecked type warning.

Here is my code:

 package sorts;

public class SortableArray<T extends Comparable<T>> {
    T[] GenList;


    public SortableArray(T[] theList) {
        GenList = theList;
    }

    public SortableArray(int[] theList) {
        Integer[] temp = new Integer[theList.length];   
        for(int i = 0; i < theList.length; i++) {
            temp[i] = new Integer(theList[i]);
        }
        GenList = (T[]) temp; //warning here
    }
}

Should I just suppress the warning, or is there a safer approach?

Thank you for your responses.


Solution

  • The reason this could be problematic is if I tried to do something like this:

    SortableArray<String> array = new SortableArray<>(new int[] { 3, 9, 9 });
    

    It looks ridiculous, but it's entirely legal, and will bite you when you want to use it somewhere else.

    What you may want to consider instead is a static factory method, which might look something like this:

    public static SortableArray<Integer> createSortableArrayFromInts(int[] theList)
    {
        Integer[] temp = new Integer[theList.length];   
        for(int i = 0; i < theList.length; i++) {
            temp[i] = Integer.valueOf(theList[i]);
        }
        return new SortableArray<Integer>(temp);
    }