转自:
下文笔者讲述java中冒号运算符的功能简介说明,如下所示:
冒号运算符的功能:
1.跳转
2.三元表达式
3.迭代循环
4.断言
5.switch
6.方法(jdk8)
例
1 跳出标签 label: for (int i = 0; i < x; i++) { for (int j = 0; j < i; j++) { //业务代码 } } 2 三元条件 int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8 3 每个循环 String[] ss = {"hi", "there"} for (String s: ss) { print(s); } 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 switch switch (type) { case WHITESPACE: case RETURN: break; case NUMBER: print("got number: " + value); break; default: print("syntax error"); } 6 方法参考 class User { public static int compareByAge(User a, User b) { return a.birthday.compareTo(b.birthday); }} } Arrays.sort(users, User::compareByAge);