比较Java中Character类型的两个对象
要比较Java中Character类型的两个对象,请使用compareTo()
方法。
首先,我们创建了两个字符类型。
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("两者相等!"); } 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