compareTo method for ordering integers

2019-03-01 13:26发布

问题:

I'm having a difficult time creating a compareTo() method for my program. My program reads 5 pairs of String/Integers from the commandline. They will represent names and ages for a Person object.

For instance my commandline arguments are: Asia 19 Java 20 Html 25 CSS 18 Ruby 10

My goal is to display them in a dialog box rearranged from smallest to biggest number.

*The problem I need help with is with my compareTo() method. I'm kinda of stuck at this point, as I just don't think I understand the concept of using this method. If someone can give me a informative explanation that would be awesome! My code:

// To display dialog box(s)
import javax.swing.JOptionPane;
//An interface used to compare two objects.
import java.lang.Comparable; 

public class searchSort{
   public static void main(String[] args){
      if (args.length != 10){
         System.out.println("Please enter 5 String/Intger pairs " +
            "on the commandline");
      }
      else{
         int age1 = new Integer(0);
         int age2 = new Integer(0);
         int age3 = new Integer(0);
         int age4 = new Integer(0);
         int age5 = new Integer(0);
         try{
            age1 = Integer.parseInt(args[1]);
            age2 = Integer.parseInt(args[3]);
            age3 = Integer.parseInt(args[5]);
            age4 = Integer.parseInt(args[7]);
            age5 = Integer.parseInt(args[9]); 
         }
         catch (NumberFormatException exception) {
            System.out.println("Error: Commandline arguments 2,4,6,8,10 must be a positive integer.");
            System.exit(0); // end program
         }

         Person[] arr = new Person[5];
         arr[0] = new Person(args[0], age1);
         arr[1] = new Person(args[2], age2);
         arr[2] = new Person(args[4], age3);
         arr[3] = new Person(args[6], age4);
         arr[4] = new Person(args[8], age5);

         JOptionPane.showMessageDialog(null, arr[0]+ "\n" +arr[1]+ "\n"+arr[2]+ "\n"+
            arr[3] + "\n" + arr[4]);

         // 
      }
   }
}
class Person implements Comparable{
// Data Fields
   protected String name;
   protected int age;

   // Constructor
   public Person(String n1, int a1){
      name = n1;
      age = a1;
   }

   //toString() method
   public String toString(){
      String output = name + " is " + age + " years old.";
      return output;
   }

   //getAge() method
   public int getAge(){
      return age;
   }

   // compareTo() method   
   public int compareTo(Object object) throws ClassCastException{
     int person1 = this.getAge();
     int person2 = object.getAge();
      int result = this.getAge() - object.getAge(); 
      return result;
   }

}

回答1:

Your code won't compile, because you're using an Object as a Person. You need to cast it:

public int compareTo(Object object) throws ClassCastException{
    return age - ((Person)object).age;
}

And you only need one line, and you can access fields directly.



回答2:

The contract for the compareTo(Object obj) method demands that you return:

  • n < 0 if this is to be considered less than obj
  • 0 if this is equal to obj
  • n > 0 if this is greater than obj

This way you can define sorting behavior for your class.

Arrays.sort(people);

Note that you can sort your objects backwards by just inverting the sign of the return value.

As a side note, some sorting methods allow you to pass a Comparator along with the collection you want to sort, which enables you to define a different sort criterion other than the default one.

Arrays.sort(people, new Comparator<Person>() { ... });


回答3:

What the Comparable enables is for you to sort Person objects when they're in a container object like a List or an Array.

I suggest looking at the Arrays and Collections classes for how to do this.