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

1
  • Look at the first answer in the "Related" sidebar on the right Commented Sep 3, 2013 at 6:23

2 Answers 2

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

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

2 Comments

That is not the proper way either.
@RohitJain I think he wanted to show an example for wrong code?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.