Hi to all,
    It’s one of the question in test, I am confused please someone help. 



MainClass{


        Public static void main(String []  a){
        Employee e=new Employee();
        for(int i:e){
          // Something   
       }



Now If I compile this code I will get an error. But without changing for each condition I want to  construct an Employee class and solve the error.

In foreach only I can iterate over an array or Iterable. Then how it’s possible.

Thanks,

Recommended Answers

All 3 Replies

In order to use foreach, the collection your iterating over needs to implement Iterator. Also, the datatype inside your foreach needs to match whatever datatype the collection is containing.

So, now you know that Employee implements Iterator and it iteratates over integers. There are a number of ways you can make Employee do this, such as inheriting from a class that already does this (like a list), or just doing it yourself.

I want to construct an Employee class and solve the error.

Before you get bogged down in Java syntax, think about the meaning of what you are trying to do. You can read a for each in English like this:

for(int i:e){
// for each int (which I will call i) in the array or collection of ints called e...

now what sense does it make to say

for each int in this Employee

?

What multiple ints does an Employee have? Employee isn't an array or collection?

as they say: there is no doubt, only do.

And what you should do is learn to crawl before you can walk, learn to walk before you can run.

Learn the basics of the language, and you'll understand James' explanation of where you went wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.