** ① compareTo () ** when comparing by character string
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));
}
}
Below is the execution result.
-1
1
0
Returns -1 or 1 if the characters are lexicographically separated. -1 because a is before b b is after a, so 1 0 if they are the same
** ② Integer.compare () ** for numerical comparison
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));
}
}
Below is the execution result.
-1
1
0
Simply the calculation result. 1-2=-1 2-1=1 1-1 = 0.
Recommended Posts