The Artima Developer Community
Sponsored Link

Java Answers Forum
Vector ClassCast exception when looping

2 replies on 1 page. Most recent reply: Apr 6, 2005 7:59 AM by Will

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Will

Posts: 20
Nickname: lofty
Registered: Mar, 2005

Vector ClassCast exception when looping Posted: Apr 6, 2005 7:39 AM
Reply to this message Reply
Advertisement
I'm having a few problems looping through a vector - I can see the problem is that I'm trying to cast an object to a string, but I don't know what to do to fix it - can anyone help?

Vector seed = new Vector(5, 2);
Iterator sIt = seed.iterator();
seed.add(new GrassSeed("TT10"));
seed.add(new GrassSeed("TT21"));


for (Iterator i = seed.iterator(); i.hasNext();) {
String name = (String) i.next();
System.out.println(name);


Thanks.


Amol Brid

Posts: 43
Nickname: amolbrid
Registered: Feb, 2004

Re: Vector ClassCast exception when looping Posted: Apr 6, 2005 7:49 AM
Reply to this message Reply
Hi,

You cannot cast to String because you have added objects of GrassSeed in Vector. You code should be something like this:
for (Iterator i = seed.iterator(); i.hasNext();) {
    GrassSeed gs = (GrassSeed) i.next();
    System.out.println(gs.getName());
}

where getName() method will return the string passed to the constructor of GrassSeed.

Regards,
Amol Brid.

Will

Posts: 20
Nickname: lofty
Registered: Mar, 2005

Re: Vector ClassCast exception when looping Posted: Apr 6, 2005 7:59 AM
Reply to this message Reply
Ah, that's got it - brilliant, many thanks :)

Flat View: This topic has 2 replies on 1 page
Topic: Layoutmanager Previous Topic   Next Topic Topic: Driver documentation / SQL Errro codes

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use