JordyV
JordyV

Reputation: 389

Generic methods don't work with 'int' type variable?

I'm having some trouble with the two variables: int and Integer. They're roughly the same, but (as shown in the code below) they don't always act the same. Here's my problem: This piece of code works just perfect. I've made a generic method, printArray which needs an array of any kind of variable (since it is generic) in order to work. Here I use the variable type Integer. But, when I change my type of array 'getal' to int (instead of Integer), the method printArray doesn't work annymore. Why is that? Do generic methods not work with int type variables?

package Oefenen;

public class printArray
{
    public static void main (String args[])
    {
        Integer[] getal = {10, 20, 30, 40, 50};
        printArray(getal);  
    }

    public static <E> void printArray (E[] intArray)
    {
        for (E element : intArray)
        {   
            System.out.printf("%s\n", element);
        }
    }
}

ps: If I change the generic method to a method only for int's, it does work. So I was thinking the problem is : Generic methods do not work with int's. Am I

Upvotes: 4

Views: 3875

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- Though Generic can be used with class, methods, variables, interface but one of the main reason of using Generics is to make Collection Type-Safe.

- Generics deals with only Objects. int is a primitive type, but Integer are Wrapper Objects. Due to AutoBoxing which was introduce from Java 5, you are not able to find the difference while you move from int to Integer or vice-versa.

- In Collection also when we use Generics, then Wrapper objects are used.

Upvotes: 1

Andy
Andy

Reputation: 1994

Generics work only for real Types, int is a primitive type (like float, double, ...)

You may, however, use autoboxing, e.g.

int primitiveInt = 1;

// this will 'autobox' (transform) the primitive type to a real type.
Integer typedInt = primitiveInt;

The other way around works, too, but be aware of possible NullPointerExceptions, because a real type may be null, which is not handled by autoboxing. (a primitive type has always a default value)

Upvotes: 1

Jerome
Jerome

Reputation: 2174

Generics works only for classes. int, as double, float, etc... are not classes

Upvotes: 5

RNJ
RNJ

Reputation: 15552

Generic methods only work with subtypes of Object. Integer is a sub type of Object. int is not an object but a primitive. So this is expected behaviour. This link is quite useful

This related question may also be useful

Upvotes: 10

Related Questions