compareTo方法是怎么利用字典顺序比较两个字符的呢?jdk中说该比较基于字符串中各个字符的 Unicode 值,下面是一个compareTo的方法举例
class Testenum
{
public enum Season{fall,winter,spring,summer};
public static void main (String[] args) {
//declare two variables of type enum String;initialize
//the variables
Season s=Season.winter, t=Season.spring;
//equals() tests the value of s
if(s==Season.winter||s==Season.spring)
System.out.println("In"+s+"economy fares apply");
//compareTo() affirms the ordering of the seasons
if(s.compareTo(t)<0)
System.out.println(s+"comes before"+t);
}
}
为什么第二个输出是wintercomes beforespring呢?
winter和spring是怎么比较的呢?
class Testenum
{
public enum Season{fall,winter,spring,summer};
public static void main (String[] args) {
//declare two variables of type enum String;initialize
//the variables
Season s=Season.winter, t=Season.spring;
//equals() tests the value of s
if(s==Season.winter||s==Season.spring)
System.out.println("In"+s+"economy fares apply");
//compareTo() affirms the ordering of the seasons
if(s.compareTo(t)<0)
System.out.println(s+"comes before"+t);
}
}
为什么第二个输出是wintercomes beforespring呢?
winter和spring是怎么比较的呢?
解决方案 »
- 高分请人!!求把这工具中的C实现的代码改成JAVA的!!!!
- webservice异常 谁见过
- 求助一道简单的考试题的最佳答案,表达式怎么处理最有效率呢?
- eclipse运行时只停留在启动界面,这是为什么??
- 请问一下大连东软的商用事业部和社报事业部都怎么样
- 我写了个判断是不是中文的小程序!想请教有没有更好的方法!200分
- Java App 在 IBM AIX 上的中文显示问题
- 简单问题,送分
- 请问各位高手,JB自动生成的代码里面一个问题
- 那又能在ie中用的Tree控件?或Tree控件的源码?
- (求助)音乐处理小问题,event.getType()
- windows下 JDK1.5 的JAVA虚拟机支持多大内存,提示Could not reserve enough space for object heap
compareTo
public final int compareTo(E o)
Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared. Specified by:
compareTo in interface Comparable<E extends Enum<E>>
Parameters:
o - the object to be compared.
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.也就是说比较的是s.ordinal()和t.ordinal()
String str2=t.toString();
if(str1.compareTo(str2)<0)
System.out.println(s+"comes before"+t);
这是字典排序的定义。如果这两个字符串不同,那么它们要么在某个索引处的字符不同(该索引对二者均为有效索引),要么长度不同,或者同时具备这两种情况。如果它们在一个或多个索引位置上的字符不同,假设 k 是这类索引的最小值;则在位置 k 上具有较小值的那个字符串(使用 < 运算符确定),其字典顺序在其他字符串之前。在这种情况下,compareTo 返回这两个字符串在位置 k 处两个char 值的差,即值: this.charAt(k)-anotherString.charAt(k)
如果没有字符不同的索引位置,则较短字符串的字典顺序在较长字符串之前。在这种情况下,compareTo 返回这两个字符串长度的差,即值:
this.length()-anotherString.length()
比较的是order
public enum Season{fall,winter,spring,summer};
也就是第一个元素的order是0,第一个是1等等,依此类推,这跟C的枚举类型相似
通过ordinal()方法可以获得相应的order,即s.ordinal()和t.ordinal()