Groovy - 关系运算符


关系运算符允许对对象进行比较。以下是 Groovy 中可用的关系运算符 -

操作员 描述 例子
== 测试两个对象之间的相等性 2 == 2 将给出 true
!= 测试两个对象之间的差异 3 != 2 将给出 true
< 检查左侧对象是否小于右侧操作数。 2 < 3 将给出 true
<= 检查左侧对象是否小于或等于右侧操作数。 2 <= 3 将给出 true
> 检查左侧对象是否大于右侧操作数。 3 > 2 将给出 true
>= 检查左侧对象是否大于或等于右侧操作数。 3 >= 2 将给出 true

以下代码片段显示了如何使用各种运算符。

class Example { 
   static void main(String[] args) { 
      def x = 5;
      def y = 10;
      def z = 8;
		
      if(x == y) { 
         println("x is equal to y"); 
      } else 
         println("x is not equal to y"); 
			
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
				
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
					
      if(z<y) { 
         println("z is less than y"); 
      } else 
         println("z is greater than y"); 
						
      if(x<=y) { 
         println("x is less than y"); 
      } else 
         println("x is greater than y"); 
			
      if(x>y) { 
         println("x is greater than y"); 
      } else 
         println("x is less than y"); 
			
      if(x>=y) { 
         println("x is greater or equal to y"); 
      } else 
         println("x is less than y"); 
   } 
} 

当我们运行上面的程序时,我们将得到以下结果。从如上所示的算子描述中可以看出,结果符合预期。

x is not equal to y 
z is not equal to y 
z is not equal to y 
z is less than y
x is less than y 
x is less than y 
x is less than y 
groovy_operators.htm