2 Replies Latest reply: Jul 23, 2013 1:45 PM by olarguz RSS

    Array creation in generic method.

    olarguz

      I have next class.

       

      public class Data implements Comparable<Data>

      {

          private int val;


          public Data(int val)

          {

              this.val = val;

          }

       

          public int getVal()

          {

              return val;

          }

       

         public void setVal(int val)

          {

              this.val = val;

          }

       

          @Override

          public int compareTo(Data o)

          {

              return val - o.val;

          }  

      }

       

      And I need create a duplicated array of Data object in a method which is a template with variable type

       

      public class CopyClass

      {

          public static int[] duplicate ( int[] data)

          {

              int array[] = new int [data.length * 2];

             

              for (int i = 0; i < data.length; i++)

              {

                  array[2*i] = data[i];

                  array[2*i+1] = data[i];

              }

             

              return array;

          }

         

          public static<T extends Comparable<? super T>> T[] duplicate ( T[] data)

          {

              T array[] = (T[])new Object [data.length * 2];

             

              for (int i = 0; i < data.length; i++)

              {

                  array[2*i] = data[i];

                  array[2*i+1] = data[i];

              }

             

              return array;

          }

         

          public static void logg ( int[] data)

          {

              String msg = "{";

              for (int d : data)

              {

                  msg += " " + d;

              }

              msg += "}";

              System.out.println(msg);

          }

         

          public static void main (String []args)

          {

              int [] val = { 7, 14, 2};

              int [] vals = duplicate(val);

              logg(val);

              logg(vals);

             

              Data[] data = {new Data(7), new Data(14), new Data(2)};

              Data[] datas = duplicate(data);

          }

      }

      Firts duplicate method works fine because it has a integer array as parameter an return an array whom values are duplicated.

      Second duplicate methos don't works.

      { 7 14 2}

      { 7 7 14 14 2 2}

      Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

        at analisis.utilidades.CopyClass.duplicate(CopyClass.java:30)

        at analisis.utilidades.CopyClass.main(CopyClass.java:60)

      Java Result: 1

       

      Who I can create this kind of objects arrays?