Java 冒号 (:) 运算符有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2399590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:03:26  来源:igfitidea点击:

What does the colon (:) operator do?

javafor-loopforeachoperatorscolon

提问by lemon

Apparently a colon is used in multiple ways in Java. Would anyone mind explaining what it does?

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

For instance here:

例如这里:

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

How would you write this for-eachloop a different way so as to not incorporate the :?

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

采纳答案by Randy Sugianto 'Yuku'

There are several places colon is used in Java code:

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

1) Jump-out label (Tutorial):

1)跳出标签(教程):

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) Ternary condition (Tutorial):

2)三元条件(教程):

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

3) For-each loop (Tutorial):

3)for-each循环(教程):

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

4) Assertion (Guide):

4)断言(指南):

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) Case in switch statement (Tutorial):

5)switch语句中的案例(教程):

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

6) Method references (Tutorial)

6)方法参考(教程

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

Arrays.sort(persons, Person::compareByAge);

回答by lemon

It is used in the new short hand for/loop

它用于新的简写 for/loop

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

and the ternary operator

和三元运算符

list.isEmpty() ? true : false;

回答by Claudiu

There is no "colon" operator, but the colon appears in two places:

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

1: In the ternary operator, e.g.:

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

int x = bigInt ? 10000 : 50;

In this case, the ternary operator acts as an 'if' for expressions. If bigInt is true, then x will get 10000 assigned to it. If not, 50. The colon here means "else".

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

2: In a for-each loop:

2:在 for-each 循环中:

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

This sets x to each of the values in 'vals' in turn. So if vals contains [10, 20.3, 30, ...], then x will be 10 on the first iteration, 20.3 on the second, etc.

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

Note: I say it's not an operator because it's just syntax. It can't appear in any given expression by itself, and it's just chance that both the for-each and the ternary operator use a colon.

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

回答by Mike Cialowicz

It's used in for loops to iterate over a list of objects.

它在 for 循环中用于迭代对象列表。

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

Think of it as a for <item> in <list>in Python.

把它想象成for <item> in <list>Python 中的 a。

回答by Ritwik Bose

The colon actually exists in conjunction with ?

冒号实际上与 ?

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

is equivalent to:

相当于:

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

Also in the for each loop:

同样在 for each 循环中:

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

literally:

字面上地:

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

回答by ultrajohn

You usually see it in the ternary assignment operator;

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

Syntax

句法

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

example:

例子:

boolean isNegative = number > 0 ? false : true;

which is "equivalent" in nature to the if else

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

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

Other than examples given by different posters,

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

you can also use : to signify a label for a block which you can use in conjunction with continue and break..

您还可以使用 : 来表示块的标签,您可以将其与 continue 和 break 结合使用。

for example:

例如:

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

回答by Randy Sugianto 'Yuku'

In your specific case,

在您的具体情况下,

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

this.listis a collection (list, set, or array), and that code assigns cto each element of the collection.

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

So, if this.listwere a collection {"2S", "3H", "4S"} then the cardStringon the end would be this string:

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

2S
3H
4S

回答by Stephen C

How would you write this for-each loop a different way so as to not incorporate the ":"?

你将如何以不同的方式编写这个 for-each 循环,以便不包含“:”?

Assuming that listis a Collectioninstance ...

假设这list是一个Collection实例......

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


I should add the pedantic point that :is not an operator in this context. An operator performs an operation in an expression, and the stuff inside the ( ... )in a forstatement is not an expression ... according to the JLS.

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

回答by helpermethod

Just to add, when used in a for-each loop, the ":" can basically be read as "in".

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

So

所以

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

should be read "For each name IN names do ..."

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

回答by helpermethod

It will prints the string"something" three times.

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

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   

for ( JLabel label : labels )                  
 {              
   label.setText("something");  

 panel.add(label);             
 }