3 Replies Latest reply: Oct 24, 2011 5:00 AM by 452196 RSS

    type casting

    864004
      Dear frnds

      the following question may sound very stupid or silly but would like to know it..

      for example i have arraylist for the class A

      is it possible to type cast the list to class B

      Thank you in advance.
        • 1. Re: type casting
          gimbal2
          Why don't you try it and see what happens?
          • 2. Re: type casting
            darke
            Assuming Foo is castable to Bar , you can do
            List<Bar> baz = (List<Bar>)(List) new ArrayList<Foo>();
            But , the simpler (and probably correct) way is just have both lists as List<Bar>
            • 3. Re: type casting
              452196
              That's not type safe. If you'd kept another reference to the list as List<Foo>() then insert an item of class Bar, or another subclass thereof, the the List<Foo> reference would contain an item which wasn't of class Foo.

              This is where "bounds" come in.
              List<Foo> lfo = new ArrayList<Foo>(10);
              List<? extends Bar> baz = lfo;
              baz.add(new Bar());  .... compilation error
              This creates a list reference which can contain a list of any subclass of Bar. It will, however, be effectively read-only.