Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2007

Tip: Looking for answers? Try searching our database.

iterator problem with List of Files

Thread view: 
Alan - 23 Dec 2007 02:52 GMT
I am trying to iterate through a List<File>, but the compiler
does not like when I try to assign the next item to a File type.  It
says that file and it.next() are incompatible types, but each item of
filelist is supposed to be of type File.  The error occurs at the
line:

File file = it.next();

    The code may be found below.  Note that the method listAllFiles
returns List<File>.

     What am I doing wrong?        Thanks, Alan

List<File> filelist = listAllFiles(directory, "*.java");

for (Iterator it = filelist.iterator(); it.hasNext();)
{
    File file = it.next();
    System.out.println(file.getName());
}
Alan - 23 Dec 2007 02:56 GMT
Never mind!  A type cast fixed it:

File file = (File) it.next();
Daniel Pitts - 23 Dec 2007 21:35 GMT
> Never mind!  A type cast fixed it:
>
> File file = (File) it.next();

A type cast is the wrong way to fix it...

You shouldn't use "Iterator it", you should have used
"Iterator<File> it".

Hope this helps.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Patricia Shanahan - 23 Dec 2007 03:22 GMT
>      I am trying to iterate through a List<File>, but the compiler
> does not like when I try to assign the next item to a File type.  It
[quoted text clipped - 16 lines]
>     System.out.println(file.getName());
> }

More simply:

for (File file: filelist)
{
    System.out.println(file.getName());
}

but if you want to do it the old way, you could indicate what the
Iterator iterates:

for (Iterator<File> it = filelist.iterator(); it.hasNext();)
{
    File file = it.next();
    System.out.println(file.getName());
}

Patricia


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.