0
1

More than 5 years have passed since last update.

compareToの大小比較について

Last updated at Posted at 2019-05-24

CompareToについて値の結果、どの比較がどの値になるか忘れてしまうことがあるので、備忘録。

①文字列で比較する場合はcompareTo()


public class Test {
    public static void main(String[] args) {
         String a = "a";
         String b = "b";
         System.out.println(a.compareTo(b));
         System.out.println(b.compareTo(a));
         System.out.println(a.compareTo(a));
    }
}

下が実行結果です。

-1
1
0

辞書的に文字の位置が離れている場合に、-1か1を返します。
aはbの前なので-1
bはaのあとなので1
同一の場合は0

②数値で比較する場合はInteger.compare()


public class Test {
    public static void main(String[] args) {
         int one = 1;
         int two = 2;
         System.out.println(Integer.compare(one,two));
         System.out.println(Integer.compare(two,one));
         System.out.println(Integer.compare(one,one));
    }
}

下が実行結果です。

-1
1
0

単純に計算結果。
1-2=-1
2-1=1
1-1=0です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1