【问题标题】:What does the colon (:) operator do?冒号 (:) 运算符有什么作用?
【发布时间】:2011-01-24 20:51:57
【问题描述】:

显然,冒号在 Java 中以多种方式使用。有人介意解释一下它的作用吗?

例如这里:

String cardString = "";
for (PlayingCard c : this.list)  // <--
{
    cardString += c + "\n";
}

你会如何写这个for-each循环以不包含:

【问题讨论】:

标签: java for-loop foreach operators colon


【解决方案1】:

由于大多数 for 循环非常相似,Java 提供了一种快捷方式来减少 编写称为 for each 循环的循环所需的代码量。

以下是每个循环的简明示例:

for (Integer grade : quizGrades){
      System.out.println(grade);
 }    

在上面的示例中,冒号 (:) 可以读作“in”。对于每个循环 完全可以理解为“对于每个整数元素(称为等级) quizGrades,打印出成绩的数值。”

【讨论】:

    【解决方案2】:

    它将打印字符串“something”三次。

    JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   
    
    for ( JLabel label : labels )                  
     {              
       label.setText("something");  
    
     panel.add(label);             
     }
    

    【讨论】:

    • 这就是上面所说的 ForEach 循环
    【解决方案3】:

    冒号在 for-each 循环中使用, 试试这个例子,

    import java.util.*;
    
    class ForEachLoop
    {
           public static void main(String args[])
           {`enter code here`
           Integer[] iray={1,2,3,4,5};
           String[] sray={"ENRIQUE IGLESIAS"};
           printME(iray);
           printME(sray);
    
           }
           public static void printME(Integer[] i)
           {           
                      for(Integer x:i)
                      {
                        System.out.println(x);
                      }
           }
           public static void printME(String[] i)
           {
                       for(String x:i)
                       {
                       System.out.println(x);
                       }
           }
    }
    

    【讨论】:

      【解决方案4】:

      在Java代码中有几个地方使用了冒号:

      1)跳出标签(Tutorial):

      label: for (int i = 0; i < x; i++) {
          for (int j = 0; j < i; j++) {
              if (something(i, j)) break label; // jumps out of the i loop
          }
      } 
      // i.e. jumps to here
      

      2)三元条件(Tutorial):

      int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8
      

      3) For-each 循环 (Tutorial):

      String[] ss = {"hi", "there"}
      for (String s: ss) {
          print(s); // output "hi" , and "there" on the next iteration
      }
      

      4) 断言 (Guide):

      int a = factorial(b);
      assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false
      

      5) switch 语句中的大小写 (Tutorial):

      switch (type) {
          case WHITESPACE:
          case RETURN:
              break;
          case NUMBER:
              print("got number: " + value);
              break;
          default:
              print("syntax error");
      }
      

      6) 方法引用 (Tutorial)

      class Person {
         public static int compareByAge(Person a, Person b) {
             return a.birthday.compareTo(b.birthday);
         }}
      }
      
      Arrays.sort(persons, Person::compareByAge);
      

      【讨论】:

      • 很好 - 我错过了一些!我什至不知道你可以命名这样的断言,非常有用。
      • 来自 .NET (C#),与所讨论的结构最接近的类比是 for-each,您对此进行了很好的解释。
      • 失败的assert 不会“退出程序”。它抛出一个AssertionError。只有当它被扔到唯一剩余的非守护线程的堆栈上并且没有被捕获时,它才会导致程序退出。
      • 如果你的目标是包含所有,那么我会添加双冒号 (::) 运算符
      • 另外,方法引用中使用了双冒号。
      【解决方案5】:

      您将如何以不同的方式编写此 for-each 循环,以免包含“:”?

      假设listCollection 实例...

      public String toString() {
         String cardString = "";
         for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
            PlayingCard c = it.next();
            cardString = cardString + c + "\n";
         }
      }
      

      我应该补充一点,: 在这种情况下不是运算符。运算符在表达式中执行操作,而 for 语句中的 ( ... ) 中的内容不是表达式……根据 JLS。

      【讨论】:

      • 我的问题是:为什么?为什么要做同样的事情?
      • @RichN - 他不想这样做,他只想知道怎么做。
      • 不是作业,我想知道怎么做,这样我才能理解逻辑
      • 其实在我(糟糕的)大学,在计算机工程学习期间,他们从来没有教过我们关于java课程中的(:)的任何东西,我后来通过看例子来学习它,不幸的是,它我现在很难把它写进我的脑海里,因为我在大学里做了所有的项目
      • 你不需要假设listCollection的一个实例;如果它能够在增强的 for 循环中使用,它必须是 Iterable 的一个实例,这意味着它将具有您在答案中调用它的 iterator() 方法。
      【解决方案6】:

      补充一点,当在for-each循环中使用时,“:”基本上可以读作“in”。

      所以

      for (String name : names) {
          // remainder omitted
      }
      

      应该读作“对于每个名字 IN names do ...”

      【讨论】:

        【解决方案7】:

        你通常在三元赋值运算符中看到它;

        语法

        variable =  `condition ? result 1 : result 2;`
        

        示例:

        boolean isNegative = number > 0 ? false : true;
        

        本质上与 if else 是“等价的”

        if(number > 0){
            isNegative = false;
        }
        else{
            isNegative = true;
        }
        

        除了不同海报给出的例子,

        您也可以使用 : 来表示一个块的标签,您可以将其与 continue 和 break 结合使用..

        例如:

        public void someFunction(){
             //an infinite loop
             goBackHere: { //label
                  for(int i = 0; i < 10 ;i++){
                       if(i == 9 ) continue goBackHere;
                  }
             }
        }
        

        【讨论】:

        • 对不起,这是一个糟糕的例子。你为什么不写 boolean isNegative = number > 0;三元条件适用于诸如 double sgn = number>0 之类的事情? 1:0;
        • @user44242 哈哈,是的,我什至不记得我为什么举这个例子了。
        • @user44242 显示这样的示例使其更简单,更好地显示条件运算符的工作原理。 "你为什么不写 boolean isNegative = number > 0;" 因为这并不能说明三元运算符的任何内容。
        【解决方案8】:

        在您的具体情况下,

        String cardString = "";
        for (PlayingCard c : this.list)  // <--
        {
            cardString = cardString + c + "\n";
        }
        

        this.list 是一个集合(列表、集合或数组),该代码将 c 分配给集合的每个元素。

        所以,如果 this.list 是一个集合 {"2S", "3H", "4S"},那么末尾的 cardString 就是这个字符串:

        2S
        3H
        4S
        

        【讨论】:

        • 感谢您的回答。这段代码怎么能重写不使用“:”?
        【解决方案9】:

        冒号实际上与?一起存在

        int minVal = (a < b) ? a : b;
        

        相当于:

        int minval;
        if(a < b){ minval = a;} 
        else{ minval = b; }
        

        同样在 for each 循环中:

        for(Node n : List l){ ... }
        

        字面意思:

        for(Node n = l.head; n.next != null; n = n.next)
        

        【讨论】:

          【解决方案10】:

          在 for 循环中用于遍历对象列表。

          for (Object o: list)
          {
              // o is an element of list here
          }
          

          把它想象成 Python 中的 for &lt;item&gt; in &lt;list&gt;

          【讨论】:

            【解决方案11】:

            没有“冒号”运算符,但冒号出现在两个地方:

            1:在三元运算符中,例如:

            int x = bigInt ? 10000 : 50;
            

            在这种情况下,三元运算符充当表达式的“if”。如果 bigInt 为真,则 x 将获得 10000 分配给它。如果不是,50。这里的冒号表示“else”。

            2:在 for-each 循环中:

            double[] vals = new double[100];
            //fill x with values
            for (double x : vals) {
                //do something with x
            }
            

            这会将 x 依次设置为 'vals' 中的每个值。因此,如果 vals 包含 [10, 20.3, 30, ...],则 x 在第一次迭代时为 10,在第二次迭代时为 20.3,以此类推。

            注意:我说它不是运算符,因为它只是语法。它不能单独出现在任何给定的表达式中,而且 for-each 和三元运算符都使用冒号只是偶然。

            【讨论】:

            • 下半年有帮助,这应该是真正的答案
            • +1 可以更详细地解释它在 for-each 循环中的作用。
            【解决方案12】:

            用于新的简写for/loop

            final List<String> list = new ArrayList<String>();
            for (final String s : list)
            {
               System.out.println(s);
            }
            

            三元运算符

            list.isEmpty() ? true : false;
            

            【讨论】:

            • 我没有意识到它是新的......它是什么时候出现的?
            • 哦……那是 6 年前的事了……在我的参考框架中并不新鲜 :D
            • 我和小猪在一起 - 六年意味着它几乎从一开始就存在。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-09-14
            • 1970-01-01
            • 2010-09-14
            • 2010-09-08
            相关资源
            最近更新 更多