1

While writing the following code I get problem at lines in It is in netbeans . Whether the array declaration is accepted . If accepted then why excepton of

      Exception in thread "main" java.lang.RuntimeException: Uncompilable source code generic array creation
            at mygenerics.Addition.<init>(MyGenerics.java:26)
at mygenerics.MyGenerics.main(MyGenerics.java:16)
    Java Result: 1

Program here

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package mygenerics;

/**
 *
 * @author SUMIT
 */

public class MyGenerics {

public static void main(String[] args)
{
    Addition<Integer> ints = new Addition<>(1,2,3);
    ints.sum();
    Addition<Double> dbls = new Addition<>(1.25,2.68,3.49);
    dbls.sum();
    System.out.println(ints.toString());
}

}
class Addition<T extends Number>
{
    **T arr[]=new T[10];**
public Addition(T... values)
{
   for(int j=0;j<values.length;j++)
   {
       int i=0;
       arr[i]=values[j];
       i++;
   }
   System.out.println(arr);
}
public <T extends Number> void sum()
{
    T sum;
    System.out.print(arr);
    for(int i = 0;i<arr.length;i++)
    {
      **sum = sum + this.arr[i];**
    }

}
}

I got Generics Array creation error

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525

2 Answers2

2

TGeneric arrays cannot be created directly in Java, because Java must know the component type in runtime, but generics due to type erasure don't know their type at runtime

T[] genericArray = (T[]) new Object[];

Here is a better way:

// Use Array native method to create array of a type only known at run time
T[] genericArray  = (T[]) Array.newInstance(componentType,length);

The first method uses weak typing - no checking is performed on any of the objects passed as an argument. The second way uses strong typing - an exception will be thrown if you try to pass an argument of different class, but you must know the component type at runtime before creating the array

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
1

The best (type safe) way of creating generic arrays in Java is:

    T[] result= (T[])Array.newInstance(ElementType.class,size);

Applied to your code, this would be:

    public Addition(Class<T> cls,T... values) {
        this.arr= (T[])Array.newInstance(cls,10);
        ...
    }

And then calls:

    Addition<Integer> ints= new Addition<>(Integer.class,1,2,3) ;
    Addition<Double> dbls= new Addition<>(Double.class,1.25,2.68,3.49) ;

The form:

    T[] result= (T[])new Object[size] ;

does not generally work.

Mario Rossi
  • 7,651
  • 27
  • 37