What Does The Colon Mean In Java?

前端 未结 5 821
北海茫月
北海茫月 2020-12-09 12:05

What does the colon mean in Java? I have this:

public static List findAllAnagrams(List words) {
    List result =          


        
相关标签:
5条回答
  • 2020-12-09 12:45

    It means one thing, it is an enhanced for loop.

    for (String i: words) 
    

    means the same things as

    for (int i = 0; i < words.length; i++) {
        //
    }
    

    Joshua Bloch, in Item 46 of his worth reading Effective Java, says the following:

    The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

    The preferred idiom for iterating over collections and arrays

    for (Element e : elements) {
        doSomething(e);
    } 
    

    When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

    0 讨论(0)
  • 2020-12-09 12:50

    It is for-each loop. When you see the colon (:) read it as "in" You can find very good explanation in Oracle docs with included examples, here

    0 讨论(0)
  • 2020-12-09 12:52

    Don't think colon(:) means anything particularly. It's just how Java designers thought to delimit parameter and expression inside improved for loop.

    for ( FormalParameter : Expression ) Statement
    

    Check Language specification for same : http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2

    0 讨论(0)
  • 2020-12-09 12:58
    (String i : words)
    

    For each item in words

    : to indicate iterator item and item as i

    so to answer - it represents for-each loop

    0 讨论(0)
  • 2020-12-09 13:06

    colon in for each loop is part of syntax, colon also appears with label

    0 讨论(0)
提交回复
热议问题