Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

int

generics

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

like image 729
JordyV Avatar asked Sep 16 '25 20:09

JordyV


2 Answers

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

like image 92
RNJ Avatar answered Sep 19 '25 10:09

RNJ


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

like image 42
Jerome Avatar answered Sep 19 '25 09:09

Jerome