Solved

meaning of for loop and multiple getters

Posted on 2014-10-28
20
128 Views
Last Modified: 2014-11-11
Hi,
I see for loop like this

for(LineOfBusiness bus: getDomain().getPart().getLines()){
if (AB.equals(bus.getCd().getOherCode())){
}

What is meaning of above for loop. I do not see initialization , condition, increment .

I see code like above quite often where they have of chain of getter methods and lose track of what object they are going against and which one they are finally getting. Is it is a good idea to draw a diagram using pen and pencil or write hierarchy with some arrows to identify super and sub classes, interfaces etc to see what finally coming out as return esp when you are looking code for the first time to fix some defects without much documentation. Are there any kind of real time practical 'has-a, is-a' kind of examples dealing with interfaces and classes preferably with chain of getters like 5, 10 of them. please advise
0
Comment
Question by:gudii9
  • 12
  • 3
  • 3
  • +2
20 Comments
 
LVL 27

Assisted Solution

by:dpearson
dpearson earned 125 total points
ID: 40408947
This kind of loop:

for(LineOfBusiness bus: getDomain().getPart().getLines()){
   ... do something with 'bus'
}

is known as a "foreach" loop.  The general pattern is like this:

for (Type variable : list-of-values) {
   ... do something with variable ...
}

Here's a simple example:

List<Integer> myList = new ArrayList<Integer>() ;
myList.add(10) ;
myList.add(20) ;

for (Integer value : myList) {
   System.out.println(value) ;
}

The "for (Integer value : myList)" hides the details of having to initialize a counter (or iterator) and manage the steps of incrementing the counter and getting the next item in the list etc.  That's all handled for you.

It's very similar to writing this code:

int size = myList.size() ;
for (int i = 0 ; i < size ; i++) {
   Integer value = myList.get(i) ;
   System.out.println(value) ;
}

which now instead becomes just this:

for (Integer value : myList) {
   System.out.println(value) ;
}

Does that make sense?

Doug
0
 
LVL 32

Accepted Solution

by:
awking00 earned 125 total points
ID: 40409004
Assume you have a folder that contains multiple Excel workbooks and those workbooks contain multiple worksheets and those worksheets contain multiple rows. Further assume you have a method to retrieve the folder (let's call it getDomain) and the folder has a method to retrieve the workbook (let's call it getPart) and the workbook has a method to retrieve the rows (let's call it getLines), then getDomain().getPart().getLines() would return the rows of the worksheet in the workbook in the folder. Now assume you want to loop through all of the rows and for each row that exists, do something. Assuming the rowtype is LineOfBusiness, then we can create a variable of type LineOfBusiness and give it the name of bus and write the loop like this -
for (LineOfBusiness bus : getDomain().getPart().getLines()) { ... }
or, in a more literal interpretation, for (the rowtype row in rows) { ... }
As for the code inside the curly brackets, assume we have a String variable named AB with a value of "abc", and that rowtypes (i.e.LineOfBusiness types) have a method (Let's call it getCd) for getting a cell within the row and a cell has a method (Let's call it getOtherCode) for getting the String value of the cell, so bus.getCd().getOtherCode would return a String value. So the code inside the if section would allow us to do something if the String value returned was equal to "abc" or something else if it did not.
In this scenario of the for-loop, we're not looking for a condition that exists or while it exists, as has been the case with many of your previous questions, we're now looking for all of the members in a group of members. Hope this helps.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40410860
I was reading below link on similar lines of thoughts

http://www.javapractices.com/topic/TopicAction.do?Id=196

I did not understand this part

 //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
By the way the excel cell value example is very good and practical. thank you
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 7

Author Comment

by:gudii9
ID: 40410873
import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    Collection<String> words = new ArrayList<>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}

Open in new window


when i tried to run above code in eclipse getting below compilation error

Multiple markers at this line
      - Type mismatch: cannot convert from ArrayList<?> to
       List<Number>
      - Cannot instantiate the type ArrayList<?>

Please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40411209
//try
    List<Number> numbers = new ArrayList<Number>();
0
 
LVL 7

Author Comment

by:gudii9
ID: 40411297
import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = (List<Number>) new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    List<Number> numbers = new ArrayList<Number>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}

Open in new window



which line. When i replaced the problematic line i am getting now more errors with words etc . please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40411302
I tried
  List<Number> words = new ArrayList<Number>();

that is also giving errors.

import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = (List<Number>) new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    List<Number> words = new ArrayList<Number>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}

Open in new window

please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40411324
How did you try it, and what errors is it giving?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40411378
I tried as below. Please find my updated code.

import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = (List<Number>) new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    List<Number> words = new ArrayList<Number>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}

Open in new window


Error is adding String values to Number list is giving compilation errors. please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 125 total points
ID: 40411392
public static void main(String... aArgs){
    //List<Number> numbers = (List<Number>) new ArrayList<>();
    List<Number> words = new ArrayList<Number>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
   // List<Number> words = new ArrayList<Number>();
   Collection<String> words = new ArrayList<String>();
0
 
LVL 35

Expert Comment

by:mccarl
ID: 40412154
The root cause of the problem is that the code that you originally used would only work on Java 7 and  above. I guess you are using Java 6 or below, hence the errors. In Java 7, the compiler allows you to omit the generic type when it can work it out from the variable that you are assigning to.

Hence, in Java 6...
List<Number> numbers = new ArrayList<Number>();

Open in new window


In Java 7, you can do this (the above is also still valid too)...
List<Number> numbers = new ArrayList<>();

Open in new window


Therefore, ozo's code is what you need for it to compile on Java 6, but note the only difference between that and your original code is the correct insertion of the generic parameter (either Number or String) inside the <> brackets
0
 
LVL 7

Author Comment

by:gudii9
ID: 40412871
Assume you have a folder that contains multiple Excel workbooks and those workbooks contain multiple worksheets and those worksheets contain multiple rows. Further assume you have a method to retrieve the folder (let's call it getDomain) and the folder has a method to retrieve the workbook

This example i can relate well because i know lot about excel workbook, sheet, cell, values as i use day to day. But when i am working with different clients like financial, banking etc when i am new to their system how to understand and remember what is getting from which getter, which object. Do i supposed to write all that on a paper which seems not effective as it sometimes takes long time and and many many methods and classes to write and confusing. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40419653
can you please advise on above.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40419665
import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = (List<Number>) new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    Collection<String> words = (Collection<String>) new ArrayList<>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}
 

Open in new window


My code looks as above. My eclipse seems using j2se 1.6 as attached. I tried all possible combinations like casting using ArrayList instead of List etc. Nothing seems working to me. Can you please post me complete working code for this example. I have attached different screenshots of the errors which are not clear to me. Please advise
TestPrj.jpg
TestPrj2.jpg
TestPrj3.jpg
TestPrj4.jpg
0
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 125 total points
ID: 40420578
I tried all possible combinations like casting using ArrayList instead of List etc. Nothing seems working to me
Well then you should try the suggestions that we have been giving you! Nowhere have we suggested to do any sort of casting. You really should read what we have suggested. But to make it (hopefully) beyond doubt about exactly what we are trying to tell you, I will bold and underline the part that you are missing...

List<Number> numbers = new ArrayList<Number>();



Can you please post me complete working code for this example
I really think that it would be more beneficial to your understanding if you try and get your code working rather than just blindly copy/paste some code that we give you. I mean we have pretty much given you the line of code that you need anyway!
0
 
LVL 7

Author Comment

by:gudii9
ID: 40420777
package eePackage;
import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
   // List<Number> numbers = (List<Number>) new ArrayList<>();
    List<Number> numbers = new ArrayList<Number>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    Collection<String> words = new ArrayList<String>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}
 

Open in new window

it worked as above and got below output
42
-30
654.2
Name : Ethan Hawke
Name : Julie Delpy
Edited words: [Il ne lui faut que deux choses: , le, et, le, temps., - Alfred de Vigny.]
Thing : blah
0
 
LVL 7

Author Comment

by:gudii9
ID: 40420780
I wonder why they defined log method as private as below. please advise

// PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
0
 
LVL 35

Expert Comment

by:mccarl
ID: 40420856
I wonder why they defined log method as private as below. please advise
Because that method is only called from within this class, it can be defined as "private". They could have defined it as "public" but it wouldn't need to be and so generally you only declare something to be restrictive as possible while still allowing the program to work.

But this is a totally different question, if you want to discuss further, please open a new question.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40421898
I got it. Can you please advise on my above comment ID: 40412871 which is still challenge in my mind.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40426478
Please advise
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question