Enhanced for-loop by java5 needs to be more  enhanced?

Hi, all of you,
I often need to iterate a collection. Sometimes I need to iterate a subset of a collection. Then I have found the enhanced for-loop is not enough.
Before Java 5, you did the following:
for(int i=0;i<collection.size();i++) {
Object object = collection.get(i);
doSomething(object);
}Thanks to Java 5, you can do the following:
for(Object object:collection) {
doSomething(object);
}However, before Java 5, I have the flexibility to skip the first two lines by purpose, as follows
for(int i=2;i<collection.size();i++) {
Object object = collection.get(i);
doSomething(object);
}What should I do the same thing with Java 5?
Kind regards.
Pengyou

pengyou wrote:
JoachimSauer wrote:
masijade. wrote:
uncle_alice wrote:
Or, if the collection is a List: for (Object obj : theList.subList(2, theList.size())) {
doSomething(obj);
Ah, yeah, I keep forgetting about that. ;-)
Actually, I just never think about it. ;-)I think you're not alone. I find that subList() is severly under-used. It simplifies a lot of operations (ever tried someList.subList(0, someIndex).clear()? Try it).The solution is nice except it might throw IndexOutOfBoundsException.Which probably means a bug somewhere else. The way to avoid runtime exceptions is to write code that doesn't put you into situations where they'll arise, not to avoid them being thrown

Similar Messages

  • Question about "Enhanced for loop"

    public class NewLoopTest{
         public NewLoopTest(){
              int result=0;                      
              int[] a=new int[20];           
              for(int i=0;i<a.length;i++){
                   a=i++;
              for(int i:a){  
    System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
                   result+=i;           
              System.out.println("-------------");
              result=0;
              for(int i=0;i<a.length;i++){
                   System.out.println("i="+i+";"+"a["+i+"]="+a[i]+";result="+result+"+"+i+"="+(result+i));
                   result+=i;
    This code counts sum of the elements of a array.
    At first I use the enhanced for loop and at second I use the traditional for.
    Enhanced for loop in sdk1.5 returns only even elements of array, am I right?

    Enhanced for loop in sdk1.5 returns only even
    elements of array, am I right?No. It covers them all.
    The i in the enhanced for loop is not the index. It's the element at the current index. You don't have access to the index in the new loop because you don't need it.
    for (int item : arr) {
        System.out.println(item);
    // is equivalent to
    for (int ix = 0; ix < arr.length; ix++) {
        int item = aa[ix];
        System.out.println(item);
    }The i in your new loop is the same as a [ i ] in the old loop.

  • How to get count from new enhanced for loop

    Is there a better way to determine the count when new enhanced for loop is used as follows:
    String[] test = new String[]{"1","2","3"};
    int count = 0;
    for(String i: test)
    count++;
    system.out.println("count: "+count);
    }

    There are cases where I need to use the count inside
    the for loop. I can keep track of the count by using
    the increment. But, then I would rather using the old
    for loop. Go ahead and use it. Are you under the assumption that the old form should be avoided?
    There is no saving in term of efficiency and readability.If there is any added efficiency in the "for each" form of the loop, it is on the micro level, and you would never notice it.
    As far as readability, look at some of the crazy solutions you've been given to avoid the general for loop, then reconsider which is more readable.

  • BUG: 10.1.3..36.73 Internal Compile Error with enhanced for loop/generics

    I get the following compiler error when using the Java 5 SE enhanced for loop with a generic collection.
    Code:
    public static void main(String[] args)
    List<Integer> l = new ArrayList<Integer>();
    l.add(new Integer(1));
    printCollection(l);
    private static void printCollection(Collection<?> c)
    for (Object e : c)
    System.out.println(e);
    Error on attempting to build:
    "Error: Internal compilation error, terminated with a fatal exception"
    And the following from ojcInternalError.log:
    java.lang.NullPointerException
         at oracle.ojc.compiler.EnhancedForStatement.resolveAndCheck(Statement.java:2204)
         at oracle.ojc.compiler.StatementList.resolveAndCheck(Statement.java:4476)
         at oracle.ojc.compiler.MethodSymbol.resolveMethod(Symbol.java:10822)
         at oracle.ojc.compiler.RawClassSymbol.resolveMethodBodies(Symbol.java:6648)
         at oracle.ojc.compiler.Parser.resolveMethodBodies(Parser.java:8316)
         at oracle.ojc.compiler.Parser.parse(Parser.java:7823)
         at oracle.ojc.compiler.Compiler.main_internal(Compiler.java:978)
         at oracle.ojc.compiler.Compiler.main(Compiler.java:745)
         at oracle.jdeveloper.compiler.Ojc.translate(Ojc.java:1486)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildGraph(UnifiedBuildSystem.java:300)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildProjectFiles(UnifiedBuildSystem.java:515)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.buildAll(UnifiedBuildSystem.java:715)
         at oracle.jdeveloper.compiler.UnifiedBuildSystem$CompileThread.run(UnifiedBuildSystem.java:893)

    Install the Service Update 1 patch for JDeveloper (using the help->check for updates), and let us know if this didn't solve the problem.

  • How do I use an enhanced for loop / for each on my ViewObjectImpl ?

    Guys and Gals,
    With all of my newly acquired Java knowledge in tow, I spent this weekend cleaning up all of my code, dealing mainly with for loops. I converted them from a huge mess to a for each type loop using language such as ...
        RowSet priceUpdateRows = (RowSet)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        { // do operations on row... which makes perfect sense to me. For each Row in the RowSet, do something. It doesn't, however, makes sense to the compiler. It pouts and gives me a "foreach not applicable to expression type" error. So I read up on iterators and such, messed with code examples, and still can't get the RowSet to iterate with the above code. Could I make RowSet implement Iterable? How would I do that? I tried to create a class called RowSetExt which extended RowSet and implemented Iterable, but then I got a class cast exception.
    I know I could implement something like the following or a while(hasNext()) but they're really not what I'm looking for.
    ViewObject vo = … < Get ViewObject > …
    RowSetIterator rsi = vo.createRowSetIterator("rowsRSI");
    while (rsi.hasNext())
         Row row = rsi.next();
         row.setAttribute("YourAttribute",your_value);
         rsi.closeRowSetIterator();How do I make the for(Row row : <RowSet>) example work? Or could someone point me in a direction?
    Will

    One thing I tried was to make a framework extension class for my ViewObjectImpls
    public class PcsViewObjectImpl
      extends ViewObjectImpl
      implements Iterable<Row>
      Set<Row> set = new HashSet<Row>();
      public Iterator<Row> getRows()
        return set.iterator();
      public Iterator<Row> iterator()
        return getRows();
    }AppModuleImpl
        PriceUpdateRowsViewRowImpl priceUpdateRows = (PriceUpdateRowsViewRowImpl)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        {However, this gives me a class cast exception at runtime. But I would think some kind of extension class would be the way to go ... ?

  • Enhance for loop question

    I like it, but I can't figure out how to use it for the following situation (printing contents of two arrays using one iterator):
    old way:
            System.out.println(menuTitle + "/n");
            for (int e ; e < length.menuChoices ; e++)
                System.out.print(menuChoices[e] + " - " + menuLabels[e]);
            }new?
            System.out.println(menuTitle + "/n");
            for (String e : menuChoices)
                System.out.print(e + " - " + menuLabels[????]);
            }Is there a nice way to do this or should I just use the old for loop and hope my teacher doesn't think that I just don't know about the new loop? Thanks.

    Is there a nice way to do this or should I just use
    the old for loop and hope my teacher doesn't think
    that I just don't know about the new loop?No there isn't. In the new for-loop the loop counter has been abstracted away. You'll have to either use the old for-loop, or introduce a counter in the new.
    Another way could be to change the design a little.
    class MenueItem {
       Type1 choice();
       Type2 label();
    for (String e : menuItems)  { // all MenuItems
       System.out.print(e.choise() + " - " + e.label());
    }

  • Enhanced for loop with DirectoryStream  in java 7

    Hi, I'm a newbie to Java and am having trouble with the following code, which I'm trying to use to iterate through a directory and obtain the file names of all the pics to create thumbnails of them.
    I've done hours and hours of searching on the web and find no answer for this one, so it's probably something very simple I've screwed up.
    All assitance is appreciated.
    The code segment:
            try (DirectoryStream<Path> ds =
              Files.newDirectoryStream(FileSystems.getDefault().getPath(dirNew)))
                  System.out.println("at dirstream");
                  System.out.format("toString: %s%n", ds.toString());
                for (Path p : ds)
                    // Iterate over the paths in the directory and print filenames
                   System.out.println(p.getFileName());
                   System.out.println("at Path p : ds");
                    thumbName = p.getFileName();
                    createThumb(String.format("%s",thumbName));
            } catch (IOException e) {
                System.out.println("dirstream failed!!!");
    //           e.printStackTrace();
                System.out.println("atend of dirstream");and the output:
    run:
    /home/rich/Images/FromWeb-Misc/1
    at dirstream
    toString: sun.nio.fs.UnixSecureDirectoryStream@196b20e
    atend of dirstream
    Edited by: 898552 on Mar 6, 2013 3:04 PM
    Edited by: 898552 on Mar 6, 2013 3:07 PM
    Edited by: 898552 on Mar 6, 2013 3:09 PM

    rp0428 wrote:
    >
    It's not entering the loop.
    >
    With the versions of NetBeans I use you can set breakpoints BEFORE and even ON the loop! Being able to set them inside a loop is just a no-cost extra. ;)I know! But you said "IN THE LOOP" :D The poor guy will set his breakpoint in it and think his debugger is broken ;)
    Relax - take a deep breath - repeat after me
    >
    5 more points - 5 more points - 5 more points
    >
    Congratulations - I see a 'shiny' future for you!
    Status Level: Expert (2,495) :DHaha, I hadn't noticed that :D I better be extra helpful now, so I can pop open a bottle of champagne tonight ;)

  • Compile Error in Enhanced For Loop

    I'm learning generic collections and for practice wrote a simple class that uses a HashMap to store data. However, I'm getting a compile error for the code that accesses the HashMap. The error and code for my class follow.
    Can anyone help?
    Thanks...
    =====================
    The compile error:
    =====================
    MapDict.java:37: package Map does not exist for( Map.Entry entry : glossary.entrySet()  )                        ^1 error=======================
    The code for my class:
    =======================
    import java.util.Scanner;
    import java.util.HashMap;
    public class MapDict
         HashMap<String, String> glossary = new HashMap<String, String>();
         public void getEntries()
              Scanner sc = new Scanner( System.in ).useDelimiter("\n");
              String moreEntries = "y";
              String word        = "";
              String definition  = "";
              while ( moreEntries.toUpperCase().equals( "Y") )
                   System.out.print("Enter word: ");
                   word = sc.next();
                   System.out.print("Enter definition: ");
                   definition = sc.next();
                   glossary.put( word, definition);
                   System.out.print("Another glossary item? (y/n) ");
                   moreEntries = sc.next();
         public void displayEntries()
              System.out.println( glossary.size() );
              // Here is where the compile error occurs:
              for( Map.Entry entry : glossary.entrySet()  )
                   System.out.println( "\nWord: " + entry.getKey() + " Definition: " + entry.getValue() );
    }

    import java.util.Scanner;
    import java.util.HashMap;I don't see java.util.Map or java.util.Map.Entry listed here....

  • Need help w/ for loop, a do loop, and a do-while loop.

    Hello I have been trying to write a program that uses a for, do, and a do-while loop, but I am having trouble. I need the program that will prompt the user to enter two numbers. The first number must be less than the second number. I need to use a "for loop", a "do loop", and a "do-while loop" to display the odd numbers between the first number and the second number. For example, if the user entered 1 and 8, the program would display 3,5,7 three different times (one for each of the loops). Please help if you can. Thanks.

    boolean2009 wrote:
    Thank all of you all for responding.Youre welcome.
    Yes this is my homework, but my major does not even involve java i just have to take the class.Not our problem.
    And yes we are suppose to have all three in one program I do not know why,So you can learn all three types of loops (there is also an enhanced for loop to learn later on).
    but I just do not understand programming nor do i really want to.Once again not our problem.
    If anybody could help it would be much appreciated. thanks.Yes, a lot of people are willing to help you. No, none of them will do it for you. What you need to do is attempt the code and when you get stuck, post your code using the code button, include error messages, indicate which lines in your code genereate those error messages and ask specific questions.

  • For-loop & iterator.remove()

    Is it possible to remove an item during iterating with for-loop?
    for (SelectionKey opKey : selector.selectedKeys())
         // I need to remove opKey from selectedKeys set.
    }Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?

    Desiderata wrote:
    Is it possible to remove an item during iterating with enhanced-for-loop?No
    Is it really necessary to remove handled key from selectedKeys set? What will happen if I run selector.select() while selectedKeys set contains some keys?[Selector Selection|http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/Selector.html#selop]

  • Removing Items While Using New For Loop

    Consider this:
    ArrayList<String> a = new ArrayList<String>();
    ... add some stuff ...
    for(String s : a) {
    // Do some stuff
    if(some_condition) {
    a.remove(s);
    This will cause a ConcurentModificationException the a.remove(s) is ever run. Is there anyway to call the iterator.remove() method instead? The new syntax is much cleaner, and I'd like to use it, but I need to be able to call iterator.remove()
    Anyone?

    I think the code should iterate through a, putting
    references to objects in an auxillary array and then
    the loop will go through the auxilary array rather
    than the original data structure. This perfectly
    reasonable, but different implementation results in
    drastically different results (the example above would
    work fine). I see this as an issue of these general
    language features being defined to close to the metal.
    Their semantics are defined by their implementation
    not by a sound language design decision that is
    agnostic to different implementations.The enhanced for loop is defined in terms of java.lang.Iterable, a very simple interface, which can be implemented in many different ways. You can't get much farther from the metal. The concurrent modification exception is a feature of particular implementations of that interface. If you don't like those implementations, use others that behave differently. For example, you could use one of the CopyOnWrite collections implementations in java.util.concurrent, which never throw a concurrent modification exception. Your suggestion to copy the elements into an array is one (inefficient) implementation mechanism for such collections.

  • How to define function within for loop pls help?????

    Hi this is the problem i have a class, and within that class there is an actionPerformed function, in this class i also create an instance of another class, this other class also contains an actionPerformed function, which wis executed if a jButton has been pressed, when I try to place this actionPerfromed function within a for loop of a function i get an error saying illegal start of experssion, and that the class should be defined abstract as it does not define actionPerformed, when i take it out of the for loop it compliles fine, i need the function to be placed within the for loop because it needs to know the variable of the for loop, is there anyway around this? Thanks, below is the code:
    public class DisplayTransitions extends JFrame implements ActionListener
    public void add()
    for(int i = 0; i < char2.size(); i ++)
    mPanel.add(tim[i] = new JButton("Time"));
    tim.addActionListener(this);
    public void actionPerformed(ActionEvent ae)
         if (ae.getSource() == tim[i])
              timeIncr();

    This is your for loop using an anonymous inner class for the listener:
                for (int i = 0; i < char2.size(); i++) {
                    mPanel.add(tim[i] = new JButton("Time"));
                    tim.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == tim[i]) {
    timeIncr();
    Learn more about anonymous inner classes from a good Java book or the Java tutorial (try http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-answers.html).

  • Unable to put a timed structure in a parallel for loop, error -808

    If I try to place a Timed Structure in a Parallel For Loop, the TS needs a different structure name per instance to prevent collisions. However, setting the Structure Name node  to something unique per instance doesn't work, I get error -808. Have I missed something?
    Thoric (CLA, CLED, CTD and LabVIEW Champion)

    That got me thinking - something to do with the number of compiled parallel instances.
    Indeed, the compiler creates a number of parallel instances of the for loop in the compiled code (in my case 8), and uses the number requested at the Parallel Instances terminal (just under the Iterations terminal), which is set to 2. Therefore the compiler has created 8 instances of the Timed Structure, each in its own for loop instance, but they all have the same defined Structure Name. When launched, there is an immediate conflict because they can't share the same name, and error -808 is launched before the set Structure Name function can change it. Hence the error still shows when requesting only one instance, because the other seven still exist.
    I guess this means you can't have Timed Structures (or Timed Loops for that matter too) in a Parallelised For Loop?
    Thoric (CLA, CLED, CTD and LabVIEW Champion)

  • Help in script logic - problem in FOR loop

    Hi Experts,
    We are using BPC 7.5 SP08. I have written a FOR loop in script logic default.lgf which is as follows:
    *FOR %TIM_MEM%=%TIME_SET%
    *XDIM_MEMBERSET TIME =%TIM_MEM%
    *WHEN P_ACCT2
    *IS "OSDU"
    REC(EXPRESSION=[P_ACCT2].[ASSTCAINVURO][P_ACCT2].[COGSUPRVIPSA]/[P_ACCT2].[ASSTUPRVTAQTY],P_ACCT2="COGSUIPSAO")
    *ENDWHEN
    *COMMIT
    *NEXT
    As per my requirement, all this members: [ASSTCAINVURO], [COGSUPRVIPSA], [ASSTUPRVTAQTY] exists for months September to next year's August. But in my input schedule, the months are from August to next year's July(which is the company's fiscal year). Consequently the loop runs for month August to next year's July while I need to run the loop 1 month late(i.e. September to next year's August). This was achieved earlier by hard-coding the time members which we cannot afford as this requires to update these hard-coded member IDs every year.
    We have also tried using the "NEXT" property of TIME dimension as follows:
    *XDIM_MEMBERSET TIME =%TIM_MEM%.NEXT
    but %TIM_MEM%.NEXT doesn't get the month in 'NEXT'.
    Please suggest if there is any way out to solve this problem.
    Thanks in advance.

    Hi Appu,
    Even if you restrict the scope using the XDIM statement, your script will just run the number of times as per the for loop. Actually, in reality, the same calculation is happening again and again, in your code; since your calculation is not based on the time member.
    To use the for loop effectively, you need to incorporate the time member in your calculation.
    Please look at the below sample code:
    *XDIM_MEMBERSET TIME = %TIME_SET%
    *FOR %TIM_MEM%=%TIME_SET%
       *WHEN P_ACCT2
       *IS "OSDU"
          *REC(EXPRESSION=<CALCULATION>,P_ACCT2="COGSUIPSAO")
       *ENDWHEN
    *NEXT
    And in your calculation, you can use statements like
    ([P_ACCT2].[ASSTCAINVURO],TMVL(1, [TIME].[%TIM_MEM%]))
    This will ensure that everytime (as per the for loop), the calculation works on separate set of data.
    Hope you got the idea.

  • Force Multiple For Loops to run Sequentially

    I have the following sequence of 3 for loops, and I need the last for loop to execute after the other two have properly incremented the *in pointer, and that they are through executing before the data begins processing in the third loop. The purpose of the 1st 2 loops is just to skip over header data.
    #include <math.h>
    #include <stdint.h>
    #include "xilly_debug.h"
    #define SKIPBYTES 896
    #define SKIPCOUNT 448 // (896/2)
    // When creating data cube, it is helpful to discard unneeded bands.
    #define SHORTEST_BAND_TO_INCLUDE 171 // Must be between 1 and 519
    #define SHORTEST_SKIPCOUNT 119016 // (171*696*2/2)
    #define LONGEST_BAND_TO_INCLUDE 453 // Must be between 2 and 520, greater than SHORTEST_BAND_TO_INCLUDE
    #define LONGEST_SKIPCOUNT 46632 // (67*696*2/2)
    #define PROCESSCOUNT 196968 // (283*696*2/2)
    // BANDS = LONGEST_BAND_TO_INCLUDE - SHORTEST_BAND_TO_INCLUDE + 1;
    #define BANDS 283
    #define RADIANCE_SCALING_FACTOR 100
    uint16_t radCorr(uint16_t unCorrPixel, int coeffIndex){
    uint16_t corrPixel; //Holder for the corrected pixel value
    float a2, b2, c2; //Intermediate variables for the actual calculations
    if (coeffIndex > 282)
    coeffIndex = 0;
    c2 = cf[coeffIndex];
    a2 = (float) unCorrPixel;// * cf_mn;//L0R
    b2 = a2*c2*RADIANCE_SCALING_FACTOR;
    corrPixel = *((uint16_t *) &b2); // Convert float to uint16_t
    return corrPixel;
    void xillybus_wrapper(int *in, int *out) {
    #pragma AP interface ap_fifo port=in
    #pragma AP interface ap_fifo port=out
    #pragma AP interface ap_ctrl_none port=return
    uint32_t a1; //Holds input data
    uint16_t x1; //Holds input after converting to float; input to function
    uint16_t y1; //HOlds output of function, to return to processor
    static int n = 0; //Index for correlation matrix
    static int i = 0;
    // Handle input data
    //Skip over SKIPBYTES
    for(i = 0; i < SKIPCOUNT; i++){
    *in++;
    if(i<20){
    xilly_puts("Skipcount Index Value:\n");
    xilly_decprint(n, 5);
    xilly_puts("\n");
    xilly_puts("Value of *in pointer:\n");
    xilly_decprint(*in, 5);
    xilly_puts("\n");
    //Discard Lower Bands
    for(i = 0; i < SHORTEST_BAND_TO_INCLUDE; i++){
    *in++;
    if(i<20){
    xilly_puts("Shortest Band to Include Index Value:\n");
    xilly_decprint(n, 5);
    xilly_puts("\n");
    xilly_puts("Value of *in pointer:\n");
    xilly_decprint(*in, 5);
    xilly_puts("\n");
    n++;
    for (i = 0; i < PROCESSCOUNT; i++) {
    a1 = *in++;
    x1 = *((uint16_t *) &a1); // Convert uint32_t to uint16_t
    if(i<20){
    xilly_puts("Processing Loop Iteration (i) Value\n");
    xilly_hexprint(i, 5);
    xilly_puts("\n");
    xilly_puts("Input Value To radCorr Function:\n");
    xilly_hexprint(x1, 5);
    xilly_puts("\n");
    xilly_puts("Index Value Before Function:\n");
    xilly_decprint(n, 5);
    xilly_puts("\n");
    xilly_puts("Value of *in pointer:\n");
    xilly_decprint(*in, 5);
    xilly_puts("\n");
    // xilly_puts("Coefficient Value Function:\n");
    // xilly_decprint(cf[n], 5);
    // xilly_puts("\n");
    // Run the calculations
    y1 = radCorr(x1, n++);
    if(i<20){
    xilly_puts("Index Value after Function:\n");
    xilly_decprint(n, 5);
    xilly_puts("\n");
    // Handle output data
    xilly_puts("Returned Value from Function:\n");
    xilly_hexprint(y1, 5);
    xilly_puts("\n");
    xilly_puts("\n");
    *out++ = y1;

    all loops are accessing a shared resource (*in++) with read consequences. It would be difficult to imagine HLS would schedule these in parallel. If you want to make sure, I guess you can add a ap_wait() between the loops but I am pretty sure this is not necessary.

Maybe you are looking for