diego.goncalves
diego.goncalves

Reputation: 199

Why do I have to cast the returned value?

To me it seams that the function I call already returns the type I have to cast it to. Why do I have to do that?

T[]leftPart=(T[]) sort(copyOfRange(a,0,middle));

The method copyOfRange that I created supposed to return the same type as the parameter a.

Here is the code:

    static public   <T extends Comparable<T>> Object[] sort(T[] a){
    int middle=a.length/2;

    T[]leftPart=(T[]) sort(copyOfRange(a,0,middle));
    }

static public<T> T[] copyOfRange(T[] original,int from,int to){
    int size=to-from;
    T[] retObject=(T[])new Object[size];
    for(int i=0;i<size;i++) retObject[i]=original[from+i];
    return retObject;
}

Upvotes: 0

Views: 94

Answers (1)

Baalthasarr
Baalthasarr

Reputation: 367

copyOfRange returned T[], but you put it in sort() and sort() returned a Object[].

Upvotes: 3

Related Questions