1

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);
    }
}
2
  • 1
    Please format your code properly. Commented Jul 12, 2015 at 9:23
  • What does this have to do with C++? Commented Jul 12, 2015 at 9:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Cool thanks . Can you tell why int [] is not autoboxed in java ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.