0

My code snippet.

public class GenericArray <T extends Comparable<T>>{
   private T[] a;
   private int nElems;
   public  GenericArray(int max) // constructor
   {
       a=(T[])java.lang.reflect.Array.newInstance(Integer.class, max); 
       //Hard coded for Integer.
   }
}

GenericArray arr= new GenericArray<Integer>(100); 

This works, As I am instantiating explicitly passing Integer.class. How do I make this as generic ?

Or Is there a way to print Type information which passed to GenericArray using ParameterizedType ? (If I get that probably, I would handle using if statements)

2 Answers 2

2

Because of type erasure, you need to pass the Class<T> as an argument in the constructor, like

public GenericArray(Class<T> cls, int max) // constructor
{
    a = (T[]) java.lang.reflect.Array.newInstance(cls, max);
}

and pass the class in the constructor and please don't use a raw type when you use it. That is,

GenericArray<Integer> arr = new GenericArray<>(Integer.class, 100); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you . Perfect. Extending this, How Can I print the type class I am printing ? I have tried System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getClass().getCanonicalName());
-1

You can parameterized your class by passing the type like:

GenericArray<String, Integer> myobj = new GenericArray<>(“John”,2); 

Or

Consider the given code in which generic method display(), that accepts an array parameter as its argument.

class GenericArray <T extends Comparable<T>>
    {    
    public<T> display(T[] val) {       
    for( T element : val)     
    {             
     System.out.printf(“Values are: %s “ , element);    
    }   
    }
    // Declaring Array
    GenericArray[] intValue = {1, 7, 9, 15};                
    GenericArray<Integer> listObj = new GenericArray<> (); 
    // Passing Array values               
    listObj.display(intValue);

Similarly, You can declare a class with two type parameters.

Comments

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.