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是怎么比较的呢?

解决方案 »

  1.   

    自己看下API就知道了
    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() 
      

  2.   

    楼主,造成输出"wintercomes beforespring"的原因是因为if(s.compareTo(t)<0)  //这语句比较的并非是"spring"和"winter"两个字符串,比较的只是字       符"s"和"t",t的ascii码值比s大1,所以返回值为-1如果想要得到你希望的结果,可以改为:  String str1=s.toString();
      String str2=t.toString();
     if(str1.compareTo(str2)<0)
      System.out.println(s+"comes before"+t);
      

  3.   

    按字典顺序比较两个字符串。该比较基于字符串中各个字符的 Unicode 值。按字典顺序将此 String 对象表示的字符序列与参数字符串所表示的字符序列进行比较。如果按字典顺序此 String 对象位于参数字符串之前,则比较结果为一个负整数。如果按字典顺序此 String 对象位于参数字符串之后,则比较结果为一个正整数。如果这两个字符串相等,则结果为 0;compareTo 只在方法 equals(Object) 返回 true 时才返回 0。 
    这是字典排序的定义。如果这两个字符串不同,那么它们要么在某个索引处的字符不同(该索引对二者均为有效索引),要么长度不同,或者同时具备这两种情况。如果它们在一个或多个索引位置上的字符不同,假设 k 是这类索引的最小值;则在位置 k 上具有较小值的那个字符串(使用 < 运算符确定),其字典顺序在其他字符串之前。在这种情况下,compareTo 返回这两个字符串在位置 k 处两个char 值的差,即值:  this.charAt(k)-anotherString.charAt(k)
     如果没有字符不同的索引位置,则较短字符串的字典顺序在较长字符串之前。在这种情况下,compareTo 返回这两个字符串长度的差,即值: 
     this.length()-anotherString.length()
      

  4.   

    API里说清楚了
    比较的是order
    public enum Season{fall,winter,spring,summer}; 
    也就是第一个元素的order是0,第一个是1等等,依此类推,这跟C的枚举类型相似
    通过ordinal()方法可以获得相应的order,即s.ordinal()和t.ordinal()