Wednesday, June 15, 2011

How to create and initialize generic array in java ?

I recently required generic array in my project. But in java, to initialize array generically is a problem, because the way generics are implemented.

So for eg. you can't do this :
public class GenericArray<E> {
    private E a[];
    public GenericArray()
    {
        a = new E[INITIAL_ARRAY_LENGTH];
    }
}

Solution 
But still I googled and found some solutions.
Solution 1 : Use reflections
So one solution to this using reflection, and making an array at runtime and point the reference to some new array.
class GenericArray<T> {
  public GenericArray(Class<T> clazz,int capacity) { 
//Create array at runtime using reflections 
array=(T[])Array.newInstance(clazz,INITIAL_ARRAY_LENGTH);
  }

  private final T[] array;
}

Solution 2 : Use Object[] and cast to E
2nd solution is to use Object Class to solve the problem :

E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];

Or if you need value to be returned from the array at particular index try this :

public class GenericArray<E>{
private Object[] a;


public GenSet(int s) {
    a = new Object[s];
}


@SuppressWarnings({"unchecked"})
E get(int i) {
    return (E) a[i];
}
}

This solved what I needed, but not in a clean way. But if thing works, it good for us. :)


No comments:

Post a Comment

Chitika