Jan
Jan

Reputation: 1504

Java Generics return int[] instead of Integer[]

I have something like this:

public interface A<I>{
    public I[] returnAll();
}

public class B implements A<Integer>{
    public Integer[] returnAll(){

        return new int[] //return Type has to be Integer[]

    }
}

I know that Integer and int are different, since int is primitive and I also know that I can't use int as a Generic for the same reason.

Still, is there an easy way to change the generics so that I can return an int[]?

Upvotes: 1

Views: 102

Answers (3)

Hemant Metalia
Hemant Metalia

Reputation: 30648

Generics are only supported for Wrapper classes. You can not use it for primitive types.

It allows primitive types but it uses autoboxing for the same.

Generics in Java are an entirely compile-time construct - the compiler turns all generic uses into casts to the right type.

Why Generics are only supported for Wrapper classes ? : Anything that you use as generics need to be convertable to the Object.and the primitive types can not be converted to an Object. That is the reason it is not supported in generics.

EDIT :

In Java 10, there is a proposal for generics to support primitives, but not available now. (Information provided by PeterLawrey in comment )

Upvotes: 6

Tunaki
Tunaki

Reputation: 137084

An int[] is not an Integer[]. The only way would be to return I and use A<int[]> for the B class.

public interface A<I>{
    public I returnAll();
}

public class B implements A<int[]>{
    public int[] returnAll(){
        return new int[]{};
    }
}

You can't use A<int> since you can't use a primitive type as a generic type, for now (let's hope).

Upvotes: 1

maaartinus
maaartinus

Reputation: 46422

No, you can't, but you might be able to replace your interface

public interface A<I>{
    public I[] returnAll();
}

by

public interface A<AI>{
    public AI returnAll();
}

if you're dealing with the array only. Otherwise, you're out of luck. If you can use Lists instead of array's, then Guava Ints#asList can help.

Upvotes: 3

Related Questions