Java文件类int compareTo(Object o)方法与示例
文件类intcompareTo(Objecto)
包java.io.File.compareTo(Objecto)中提供了此方法。
此方法用于比较字符串对象与作为参数传递的给定对象,无论它们在字典上是否相等。
返回类型为int,这意味着如果它返回0,则字符串和给定对象都是相等的;如果它返回负值,则字符串将小于给定对象作为参数;如果它返回大于0,则字符串将为大于0。
语法:
int compareTo(Object o){
}参数:
在File方法中,我们仅传递一个对象作为参数,即任何类型的对象,无论它是字符串,整数等。此参数将与其他字符串参数进行比较。
返回值:
此方法的返回类型为int,它返回整数值(0,大于0和小于0)
Java程序演示compareTo()方法示例
//导入File类,因为我们将使用File类方法
import java.io.File;
//导入Exception类,因为它可能会引发
//处理文件时出现异常
import java.lang.Exception;
public class CompareStringWithObject {
public static void main(String[] args) {
try {
int compare;
//声明一个字符串。
String str = "Hi, We are in Java World!!";
//通过使用compareTo(“嗨,我们在Java世界中!”)"Hi, We are in Java World!!")
//此方法将返回大于0的整数
//因为Stringstr的长度将大于给定的参数。
compare = str.compareTo("Hi, We are in Java World!!");
if (compare == 0)
System.out.println("Both are equal");
if (compare < 0)
System.out.println("string str is less than given argument in the method");
if (compare > 0)
System.out.println("string str is greater than the given argument in the method");
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}输出结果
E:\Programs>javac CompareStringWithObject.java E:\Programs>java CompareStringWithObject Both are equal