• Post Reply Bookmark Topic Watch Topic
  • New Topic

Files, Iterators and ClassCastExceptions  RSS feed

 
Tristan McHardie
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the start of a program which uses a tree to represent a part of the filesystem.

I'm having trouble with the Iterator's next() method. When I call it.next(), the class of the object returned is java.io.File, even though the ArrayList it is iterating is <Directory>. I know Directory is a subclass of File (afterall, I created it) but why is it casting it back to a file in the iterator?

Here is the code for the Directory class:



Here is the code for the tree (where the problem is):



Here is my main application:



Thanks for any suggestions!
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your getSubDirectories() method, you have :
subDirectories.add(f);

You are actually inserting instances of File, not Directory.
I think that it why you have the ClassCastException.

You probably should do subDirectories.add(new Directory(f));
 
Tristan McHardie
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot, works perfectly now
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!