I have the following code which uses nested for-each loops to traverse two ArrayList properties in the Job class and the Category class (as well as performing a little logic on the properties):
for(Object dobj : hospice.getCategorys()) {
Category cat = (Category) dobj;
for(Object pobj : cat.getJobs()) {
Job job = (Job) pobj;
if(job.getID() == id) {
System.out.println(
String.format("The Job %d belongs to the (%s) %s Category.",
id,
cat.getCode(),
cat.getName()));
catFound = true;
}
}
}
Is there anyway to make use of Java Iterators with this approach to create a more elegant and future-proof solution?
Thanks.
Nested loops with iterators is OK. But more elegant solution do not use explicit cast. Preferable solution get typed iterators:
Note that in this case your methods should return typed objects
CategoryandJobbut notObject.