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

问题描述:

我会自己查看它,但我甚至不知道它叫什么。有人会介意解释它的作用吗?Java:冒号(:)运算符的作用是什么?

我不知道有多次:出现了。它有什么作用在这种情况下,在这里:

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

你会如何写这for-each循环以不同的方式,以不纳入“:”?

+4

其他人已经提到这种情况是for-each循环。有关它如何工作的更详细的解释,请参阅http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html – Jonik 2010-03-08 06:31:52

有几个地方结肠中的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 loop(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); 
+3

不错 - 我错过了一些!而我甚至不知道你可以这样命名断言,非常有用。 – Claudiu 2010-03-08 06:22:52

+0

来自.NET(C#),所讨论的结构的最接近的比喻是for-each,这是你以良好的方式解释的。 – Roger 2012-09-06 07:41:38

+1

失败的'assert'不会“退出程序”。它抛出一个'AssertionError'。它只会导致程序退出,如果它被扔在唯一剩下的非守护线程的堆栈上,并且没有被捕获。 – 2014-06-13 08:09:57

它是在新的短手用于/循环

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

和三元运营商

list.isEmpty() ? true : false; 
+0

我没有意识到它是新的...当它进来了吗? – 2010-03-08 06:17:36

+0

@Mechko,在Java 5中:http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#forloop – Jonik 2010-03-08 06:26:55

+3

哦...那是6年前...不是新的我的参考框架:D – 2010-03-08 06:40:29

没有“冒号”操作,但结肠出现在两个地方:

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

int x = bigInt ? 10000 : 50; 

在这种情况下,三元运算符充当表达式的'if'。如果bigInt是真的,那么x将得到10000分配给它。如果没有,50.这里的冒号意思是“其他”。

2:在for-each循环:

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

这设置x到各值中依次 '瓦尔斯'。因此,如果vals包含[10,20.3,30,...],那么在第一次迭代中x将为10,第二次为20.3等。

注意:我说它不是运算符,因为它只是语法。它本身不能出现在任何给定的表达式中,这只是偶然的,for-each和ternary操作符都使用冒号。

+0

下半年的帮助,这应该是真正的答案 – erp 2014-08-14 15:59:34

+0

+ 1的更详细的解释,它为每个循环做什么。 – dfarrell07 2014-09-15 18:05:19

它用在for循环遍历对象的列表。

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

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

结肠实际上结合存在具有?

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

相当于:

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

此外,在每个循环:

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

字面上:

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

你通常在三元赋值操作符中看到它;

语法

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

例如:

boolean isNegative = number > 0 ? false : true; 

在本质上是 “等价于” 如果别人

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

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

你可以n您还可以使用:来表示,而您可以在继续,并打破一起使用块标签..

例如:

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

对不起,但这是一个可怕的例子。为什么你不写 boolean isNegative = number> 0; 三元条件适用于诸如 double sgn = number> 0的情况。 1:0; – user44242 2010-03-08 07:48:02

+0

@ user44242 lol是的,我甚至不记得为什么我给了这个例子。 – ultrajohn 2015-12-31 12:17:27

在特定情况下,

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

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

所以,如果this.list是一个集合{ “2S”, “3H”, “4S”}然后在年底cardString将这个字符串:

2S 
3H 
4S 
+1

感谢您的回答。这段代码如何被重写为不使用“:”? – dukevin 2010-03-08 06:31:47

你会如何写这为 - 每个循环都有不同的方式,以便不包含“:”?

假设listCollection实例...

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

我要补充的迂腐点:是不是在这种情况下操作。一个操作符在一个表达式中执行操作,根据JLS,for语句中的(...)内部的内容不是表达式。

+0

我的问题是:为什么?为什么要做同样的事情呢? – RichN 2010-03-08 14:49:09

+2

@RichN - 他不想这样做,他只是想知道如何。 – 2010-03-08 14:57:57

+3

不作业,我想知道如何做到这一点,所以我可以理解逻辑 – dukevin 2011-02-09 21:03:10

只需添加,当在for-each循环中使用时,“:”基本上可以读作“in”。

所以

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

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

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

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

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

panel.add(label);    
} 
+1

这就是上面所说的ForEach循环 – 2015-03-20 06:14:36

结肠使用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); 
        } 
     } 
} 

由于大多数for循环是非常相似的,Java提供一个捷径,以减少写所需的 量的代码该循环称为每个循环。

这里是简明的每个循环的示例:

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

在上面的例子中,冒号(:)可以读作“在”。对于每个循环 共计可读作“为 中的每个Integer元素(称为等级)测验格式,打印出等级值。”