iterator problem with List of Files

A

Alan

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());
}
 
P

Patricia Shanahan

Alan said:
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());
}

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
 
D

Daniel Pitts

Alan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top