randomlock
randomlock

Reputation: 29

Passing int array in a Generic class

When i create a generic class object , why do i have to pass array of Integer type and not int type ? If the typed parameter can be only reference type , then why does passing an int variable work but not int array ?

class GenericA<T extends Number> {
    T arr[];

    GenericA(T o[]) {
        arr = o;
    }

    double average() {
        double sum = 0;
        for (int i = 0; i < arr.length; i++)
            sum = sum + arr[i].doubleValue();

        double average1 = sum / arr.length;

        //System.out.println("the average is" +average);
        return average1;
    }

    boolean sameAvg(GenericA<?> ob) {
        if (average() == ob.average())
            return true;
        return false;
    }
}

class GenericB {
    public static void main(String[] args) {
        Integer inum[] = {1, 2, 3, 4, 5}; //this cannot be int
        Double inum1[] = {1.0, 2.0, 3.0, 4.0, 5.0}; //cannot be double

        GenericA<Integer> ob = new GenericA<Integer>(inum);
        GenericA<Double> ob1 = new GenericA<Double>(inum1);

        boolean a = ob.sameAvg(ob1);
        System.out.println(a);
    }
}

Upvotes: 1

Views: 359

Answers (2)

M. Shaw
M. Shaw

Reputation: 1742

The fact that Java generics do not support primitives (e.g. int) is due to the JVM's implementation. Basically they aren't true generics like in C# - the information about the type is lost at runtime (search for type erasure problem). Thus Java generics are basically casts to and from Objects under the hood.

For example:

List<Integer> l = new List<Integer>();
...
Integer i = l.get(0);

would actually become

List l = new List();
Integer i = (Integer) l.get(0);

at runtime.

Upvotes: 3

Eran
Eran

Reputation: 393841

Passing an int variable where Integer is expected is possible due to auto-boxing.

However, passing an int[] where Integer[] is expected is not possible, since there's no auto-boxing for arrays of primitive types.

Upvotes: 1

Related Questions