Java: “Anonymous” array in for-each-loop

后端 未结 4 1083
感动是毒
感动是毒 2021-01-01 08:52

While I was trying something special in for loop I recognized that Java doesn\'t seem to like putting an anonymous array right as the source for a for-each-loop:

<         


        
相关标签:
4条回答
  • 2021-01-01 09:21

    The Java language provides the {"a","b","c"} form as a shortcut, but it is only possible during assignment. It's possible this is to avoid possible ambiguities during parsing, in some positions {} could be interpreted as a code block.

    The right way to do it would be how noah suggests, with new String[]{"a","b","c"}.

    0 讨论(0)
  • 2021-01-01 09:26

    You want

    for (String crt : new String [] {"a","b","c"} ) {
        doSomething();
    }
    

    I use IntelliJ and it says put the message "expression expected" on the right-hand side of the colon in the for-loop, which seems more accurate.

    I should add that IntelliJ also offers to add the "new String []" automagically for me.

    0 讨论(0)
  • 2021-01-01 09:40

    This will work:

    for (String crt : new String[]{"a","b","c"} ) {
        doSomething();
    }
    
    0 讨论(0)
  • 2021-01-01 09:45

    Dunno, what about this? :) Pity there's no succinct version. Suppose you could use Groovy or Scala if you wanted anything like that :)

    for (String s : Arrays.asList("a","b","c")) {
        hmm(s);
    }
    
    0 讨论(0)
提交回复
热议问题