在 Java 中比较两个 Character 类型的对象
java 8object oriented programmingprogramming
要在 Java 中比较两个 Character 类型的对象,请使用 compareTo() 方法。
首先,我们创建了两个 Character 类型。
Character one = new Character('m'); Character two = new Character('k');
现在,为了比较它们,我们使用了 compareTo() 方法。
int res = one.compareTo(two);
以下是比较字符对象的示例。
示例
public class Demo { public static void main(String []args) { Character one = new Character('m'); Character two = new Character('k'); System.out.println("Character object 1: "+one); System.out.println("Character object 2: "+two); int res = one.compareTo(two); if (res == 0) { System.out.println("Both are equal!"); } else if (res < 0) { System.out.println("Character 1 is less than Character 2"); } else if (res > 0) { System.out.println("Character 1 is less than Character 2"); } } }
输出
Character object 1: m Character object 2: k Character 1 is less than Character 2