Results 1 to 3 of 3
  1. #1
    Ed
    Ed is offline Senior Member
    Join Date
    Jun 2007
    Posts
    110
    Rep Power
    0

    Default ClassCastException

    I did an iterator
    I have different objects
    Some of them are cars, and other trucks (both of them are subclass of Vehicles )
    When I iterate in every element of the vector
    this error appears:

    ClassCastException

    this is my code

    Java Code:
    while it.hastnext()
     
    if (it.next() instanceof truck
     
      auxVehicle = (truck)it.next();
     
    if (it.next() instanceof Car
     
    auxVehicle = (Auto)it.next();

  2. #2
    Jack is offline Senior Member
    Join Date
    Jun 2007
    Posts
    130
    Rep Power
    0

    Default

    your code is incorrect
    when you do "ite.next" you are calling a new object inside of the list

  3. #3
    Heather is offline Senior Member
    Join Date
    Jun 2007
    Posts
    164
    Rep Power
    8

    Default

    jack is right
    I give you an example so you understand
    Java Code:
    Object obj = null;
    while (it.hasnext()) {
    obj = (Vehicle ) it.next();
    if (obj instanceof Truck
     
      auxVehicle = (Truck)obj;
     
    if (obj instanceof car)
     
    auxVehicle = (car)obj;
    }

Similar Threads

  1. ClassCastException in TreeSet
    By pHew in forum New To Java
    Replies: 2
    Last Post: 01-16-2008, 01:20 AM
  2. Replies: 1
    Last Post: 07-16-2007, 05:31 PM
  3. ClassCastException
    By Felissa in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 06:06 AM

Posting Permissions

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