Results 1 to 2 of 2
  1. #1
    JKoder70014 is offline Member
    Join Date
    Jul 2011
    Posts
    6
    Rep Power
    0

    Default Clarification On TypeCasting of ArrayList in Java

    Hi All,
    I need a clarification regarding the below code.

    1. ArrayList<Car> myCar = new ArrayList<Car>(); // Car is a java class which extends
    // Vehicle class[/b]
    2. ArrayList<Bus> myBus = new ArrayList<Bus>(); // Bus is a java class which
    //extends Vehicle class
    3. myCar.add(new Car("test"));
    4. ArrayList d = myCar;
    5. myBus = (ArrayList<Bus>)d;

    In line 5., we observe that the ArrayList d is able to be typecasted to another form of ArrayList<Bus>. I am not clear on this as if we consider the below scenario, the typecasting is not possible. Can anybody please suggest me on this..!

    Car myCar = new Car();
    Bus myBus = new Bus();
    Car car1 = (Car)myBus; // It will not compile as it cannot typecast this..!

    Thanks,
    JKoder70014

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I'm not sure what your question is exactly. Are you asking why the line
    Java Code:
    Car car1 = (Car)myBus;
    Doesn't work? Obviously an array list of busses is not a car. You can't just typecast anything to anything, it should make sense when casting.

    Also, reading up on erasure may help you understand the first part: Type Erasure
    Last edited by sunde887; 07-30-2011 at 08:01 AM.

Similar Threads

  1. Need clarification..New to java
    By Anveshan in forum New To Java
    Replies: 3
    Last Post: 09-08-2011, 09:55 AM
  2. Typecasting with Class object
    By d3n1s in forum Advanced Java
    Replies: 3
    Last Post: 05-09-2011, 09:20 PM
  3. Pblm during typecasting
    By man4ish in forum New To Java
    Replies: 2
    Last Post: 12-31-2009, 09:55 AM
  4. HELP! need clarification
    By ptsofathrty in forum New To Java
    Replies: 1
    Last Post: 12-16-2008, 09:02 AM
  5. Replies: 2
    Last Post: 04-21-2008, 12:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •