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
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
Generics works only for classes. int, as double, float, etc... are not classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With