当前位置: 代码迷 >> Java相关 >> 求教高手!!!!关于重载 compareTo 方法。
  详细解决方案

求教高手!!!!关于重载 compareTo 方法。

热度:465   发布时间:2011-03-09 14:22:43.0
求教高手!!!!关于重载 compareTo 方法。
public int compareTo(Object obj)
{            
  Customer c = (Customer)obj;
  if(c.getLastName().compareTo(lastName)   >  0   &&   c.getFirstName().compareTo(firstName)  >  0)   
  return 1;
  else if(c.getLastName().compareTo(lastName ) == 0  &&   c.getFirstName().compareTo(firstName)  >  0)
  return 1;
  else if(c.getLastName().compareTo(lastName)  == 0  &&  c.getFirstName().compareTo(firstName) == 0)
  return 0;
  else
  return -1;
}

以上是我重载的compareTo() 方法,属于在
public class Customer implement Comparable<Customer>
{
..................
}中的一个方法。                帮忙看一下,以上写的有没错误的地方?

-------------------------------------------------------------------------
以下是老师给的一个 class ..

public class Sorts
{
   //-----------------------------------------------------------------
   //  排序
   //-----------------------------------------------------------------
   public static void insertionSort (Comparable[] objects)
   {
      for (int index = 1; index < objects.length; index++)
      {
         Comparable key = objects[index];
         int position = index;

         // shift larger values to the right
         while (position > 0 && objects[position-1].compareTo(key) > 0)   
         {
            objects[position] = objects[position-1];
            position--;
         }

         objects[position] = key;
      }
   }
}

为什么运行的时候,会在重载的compareTo这个方法  和 老师给的方法 中,含有“compareTo”的地方 抛出NullPointerException异常 (打这符号的那一行) ??

求教啊~~急急急急急!!!!不懂啊~~~~
搜索更多相关的解决方案: Object  public  return  

----------------解决方案--------------------------------------------------------
public int compareTo(Object arg0) {
        Name name = (Name)arg0;
        int i = firstName.compareTo(name.firstName);
        if(i==0)
        {
            return lastName.compareTo(name.lastName);
        }
        else
        {
            return i;
        }
    }
----------------解决方案--------------------------------------------------------