5 Replies Latest reply: Apr 9, 2008 3:32 PM by 807591 RSS

    Casting generic types

    807591
      Is there a way to cast something like this?
      List rectangles = getRectangles();
      List<Rectangle> rectangles2 = (List<Rectangle>) rectangles;
      Basically, if all the objects in a List, like a hibernate query in my case, are of one type I want to be able to cast that list to a generic type. I can do the above actually without the cast and it works perfect. I just get warnings which bother me :). Is there a safe or proper way to do this?
        • 1. Re: Casting generic types
          807591
          The point of Generics is that all your project compiles without an unchecked warning, type-safe bevahiour is guaranteed and the dreaded run-time class-cast-exception will not get thrown.

          Now if that getRectangles() method returns for example a plain List, the compiler can not make such a guarantee and an unchecked warning will come.
          • 2. Re: Casting generic types
            807591
            Yes, but hibernate does not yet return generic typed Lists. So I'm forced to cast the objects within the List anyway. That's ok because I know they are going to be of a certain type. But I have to pass results to other libraries that want a List<Rectangle> (not exactly, but something similar). So I now have to wastefully copy element by element from the original List to a List<Rectangle>. There's no simple way to cast this to basically tell the compiler, "don't worry I know what I'm doing?" Or much better would be a way to actually check that the elements in the List are in fact Rectangles and then cast (I could of course do this myself if there's a way to cast).
            • 3. Re: Casting generic types
              807591
              The "unchecked" warning is just that, a warning. You should note it and check you aren't making a mistake, but if you're happy it doesn't prevent you from compiling the code.

              Or you can use the @SupressWarning("unchecked") but, if you do, do it on the smallest bit of code possible, make a private method if necessary.
              • 4. Re: Casting generic types
                807591
                Thank you malcolmmc, I'm just going to suppress the warnings as you suggest while checking for type safety manually when necessary. Is it possible to suppress the warnings for only the equivalent getRectangles() method call rather than the whole method that contains that call?

                the correct spelling of the annotation is @SuppressWarnings("unchecked")
                • 5. Re: Casting generic types
                  807591
                  No, you have to apply @SupressWarnings to a whole method, but you can (and probably should) just extract to offending line as a private method. The compiler will probably inline it anyway.