• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 420
  • 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;

 
       while(itr.hasNext())
       {
           // the line below gives an error; incompatible types, required customer, found Object
 
           c = itr.next();
           if(c.matchesID(custID))
               break;
       
       }
       return c;
    }
0
alcindor
Asked:
alcindor
1 Solution
 
CPColinCommented:
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.
0
 
alcindorAuthor Commented:
Excellent. Thanks for that, Roger
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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