Reputation: 23
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)
Upvotes: 0
Views: 411
Reputation: 205
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.
Upvotes: -1
Reputation: 201507
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);
Upvotes: 2