About size comparison of compareTo

About CompareTo As a result of the value, you may forget which comparison is which value, so make a note.

** ① 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

About size comparison of compareTo
About disconnect () of HttpURLConnection
About selection of OpenJDK
About DI of Spring ①
About DI of Spring ②
About form. ○○ of form_with
About @Accessors of Lombok
About the handling of Null
About an instance of java
About simple operation of Docker
About the description of Docker-compose.yml
About types of code coverage
Memorandum of understanding about LOD.
About partial match of selector
[Java] Speed comparison of string concatenation
About the behavior of ruby Hash # ==
String comparison without worrying about NullPointerException
Comparison of compression libraries for JavaVM
About the basics of Android development
Rotate by file size of logback
About fastqc of Biocontainers and Java
[Rails] About implementation of like function
Java comparison using the compareTo () method
About binding of Spring AOP Annotation
About the role of the initialize method
About removeAll and retainAll of ArrayList
Think about the 7 rules of Optional
About image upload of jsp (servlet)
About Disk Cache of Glide 4 series
[Ruby] Review about nesting of each
[Java] Correct comparison of String type
Explanation about Array object of Ruby
Summary about the introduction of Device
About the log level of java.util.logging.Logger