简体   繁体   中英

Nested for-loops with Iterators?

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:

for (Category cat : hospice.getCategorys()){
  for (Job job : cat.getJobs()){
    // logic here
  }
}

Note that in this case your methods should return typed objects Category and Job but not Object .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM