how to create generic parametric arrays

Question

Considering this following class

public class Pair <T, U> {
  public T first ;
  public U second ;
  public Pair (T first , U second ) {
    this . first = first ;
    this . second = second ;
  }
}

Write the method

 public static <T, U> GArray<Pair<T,U>> pair(T[] A, U[] B, int n)

which creates a GArray of pairs from the first n elements of A and B by pairing each element from A with the element from B at the same index.

public class Pair <T, U> {
  public T first;
  public U second;

  public Pair (T first , U second) {
   this.first = first;
   this.second = second;
  }

  public static <T, U> GArray<Pair<T,U>> pair(T[] A, U[] B, int n){

    GArray obj = new GArray(n);
    for(int i=0;i<n;i++){
      Pair p = new Pair(A[i],B[i]);
    obj.add(p);}

     return obj;
}

 public static void main(String[] args){

   Integer[] A = {1,2,3};
   Double[] B = {1.0,2.0,3.0};

   GArray obj = pair(A,B,2);

   obj.print();
 }

  public String toString(){
   return "Pair = (" + first + "," + second + ")";
  }

}

I did this class

public class GArray<E>{
  E[] arr;
  int size;

  public GArray(int n){
    arr = (E[]) new Object[n];
  }

  public void add(E p){
   if(size<arr.length){
    arr[size] = p;
    size++;
  }
 }

 public void print(){
    for(int i=0;i<arr.length;i++)
    System.out.println(arr[i]);
  }
}

is there any problem with this? because this would compile an error

 Pair<T,U>[] garray = (Pair<T,U>[])new Object[n];

Show source
| generics   | java   | type-parameter   2017-10-04 23:10 0 Answers

Answers to how to create generic parametric arrays ( 0 )

Leave a reply to - how to create generic parametric arrays

◀ Go back