• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 424
  • Last Modified:

Java iterator problem

The following code is indicating an error at the line c = itr.next(). I can eradicate the error by casting itr.next() as follows:

c = (Customer) itr.next();

Is this a valid way of addressing the issue ? I am a seasoned C/C++ programmer but am totally new to Java. Customer is a class

The code is as follows:
// declared at the top of the class:-
   ArrayList<Customer> customerList  = new ArrayList<>();

// code in a member function:-
   public Customer find(int custID)
    {// iterate the array, add matching results to a second array and return the second
       Iterator itr = customerList.iterator();
       Customer c = null;

           // the line below gives an error; incompatible types, required customer, found Object
           c = itr.next();
       return c;
1 Solution
CPColinSenior Java ArchitectCommented:
The Iterator interface is generic, like the ArrayList class. If you declare your variable like this, the build error should go away:

Iterator<Customer> itr = customerList.iterator();

Open in new window

The way you're doing it, with the explicit cast, is how Java programmers had to do it before the language added support for generics. It's what the language is doing in the background either way, so it's not necessarily bad, just no longer necessary.
alcindorAuthor Commented:
Excellent. Thanks for that, Roger
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now