2 Replies Latest reply on Aug 9, 2010 9:37 PM by 843793

    Array of generic type?

      public final class FloydWarshall <N extends Node> {
          private final N   [][] P;
          public FloydWarshall ( final N[] nodes, final Edge[] edges )  {
              P = (N[][])new Node[nodes.length][nodes.length];
       "Type safety: Unchecked cast from Node[][] to N[][]"
      I'm confident that this is safe, but I still don't like to suppress type warnings. Is there a "correct" way to do this? I couldn't figure out a way to write a dynamic cast for it.

      Hmmm... I see here that N[][] isn't really legal, so I guess Node[][] is better?

      But that just forces me to cast elsewhere since P[][] is now Node instead of N:
          private List<N> getIntermediatePath ( final N source, final N target )  {
              List<N> path = new ArrayList<N>();
              path.addAll( getIntermediatePath( source, P[source.index][target.index] ) );
      "The method getIntermediatePath(N, N) in the type FloydWarshall<N> is not applicable for the arguments (N, Node)"
          ... return path;
      Edited by: DMF. on Aug 8, 2010 6:41 PM
        • 1. Re: Array of generic type?
          Short answer: no way. You may instanciate generic arrays with java.lang.reflect.Array.newInstance(Class<?>, int) method. However you want an array of where the component type is a type parameter, unknown at runtime, so you cannot get an appropriate Class instance.

          I would suggest you create a NodeMatrix<N extends Node> class where the N[][] field is private and define the matrix methods you will need. These methods will yield unchecked warning but at least you have type-unsafe operations gathered in a single class. The array privacy compensates type-unsafety a bit and it will be easier to debug.
          • 2. Re: Array of generic type?
            I tried using a class literal - Class<N[][]>.class - in the argument list to provide the runtime type, but then I couldn't figure out how to construct it. clazz.newInstance() wouldn't. IIRC, arrays aren't real classes. Maybe .Array.newInstance would work. Maybe create a single dimension array, then use the class of that object to feed newInstance? Probably run into the same problem. I'll have to try it.

            I think the matrix class is overkill for this application, but I appreciate the idea.

            I guess in the end I may just have to live with the cast and warning. Thanks.