Groovy-relational-operators

提供:Dev Guides
移動先:案内検索

Groovy-関係演算子

関係演算子は、オブジェクトの比較を許可します。 以下はGroovyで利用可能な関係演算子です-

Operator Description Example
== Tests the equality between two objects 2 == 2 will give true
!= Tests the difference between two objects 3 != 2 will give true
< Checks to see if the left objects is less than the right operand. 2 < 3 will give true
Checks to see if the left objects is less than or equal to the right operand. 2 ⇐ 3 will give true
> Checks to see if the left objects is greater than the right operand. 3 > 2 will give true
>= Checks to see if the left objects is greater than or equal to the right operand. 3 >= 2 will give 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