Rgds : Sort by compareTo interface Comparable.

Hi , i got a txt file call Summary.txt
which record the following
[playerName,NumberOfAttempts]
eg:
jack,2
peter,1
albert,6
jammy,5
jean,2
tester1,9
lordz,7
My question is " How Do I Sort by Implements Comparator interface " ,
I DO search the forum on information but most of the thread is about Obj in form of Integer , mine records is record in this way
[font color=red]
Then they only compare Object 1 and Object 2 , i want is compare all the numerOfAttempts record in my Summary.txt then arrange in ASCending order.
[font]
playername,numberOfAttempts means i need use StringTokenizer to break the string into 2 tokens
namely playerName and numberOfAttempts .
Firstly , how do i set playerName & numberOfAttempts together but sort only by numberOfAttempts . After sort , i can display out the playerName.
I was advised to create 2 Objects Array but got people reply that it is dumb to do so , then i search on the advised Comparable but i never see a string example.
anyone can help me?
To be specific what i want is :
Firstly => Obtain the String in form of
First Token = PlayerName
Second Token = numberOfAttempts
THEN sort by numberOfAttempts.
Lastly => Display Top 10 ranking as in form of
LEAST numberOFAttempts = at the most best rank.
1. playerName - numberOfAttempts
2. playerName - numberOfAttempts
null
Message was edited by:
baoky

I seen the code and this code is working fine. but theres 1 thing problem .
Firstly => The System.out.println print a whole straight line of values which is sorted .
But what i want to do is actually
=> jtaLog.append("1. " playerName numberOfGuess);
In the vector form i cant really append in that way.
I learn that Vector got a code method that is
copyInto
public void copyInto(Object[] anArray)
How do i create Object that record from the Vector after sort and append the top 10 list of playerName","noOfGuess to my jtaRanking.
Sorry for the trouble and thanks for the code , I had it read and understand how it works.
import java.io.*;
import java.util.*;
public class sortby {
     public sortby() {
          //super();
          // TODO Auto-generated constructor stub
      * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          try {
               BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("summary.txt")));
               String linedata="";
               Vector v=new Vector();
               while((linedata=br.readLine())!=null)
                    StringTokenizer tok=new StringTokenizer(linedata,",");
                    if(tok.countTokens()>=2)
                         String val=tok.nextToken();
                         String num=tok.nextToken();
                         player p=new player();
                         p.setName(val);
                         p.setAttemps(num);
                         v.add(p);
               Collections.sort(v,new mycompare());
               System.out.println(v);
          } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
class player
     private String name;
     private String attemps;
     public String getAttemps() {
          return attemps;
     public void setAttemps(String attemps) {
          this.attemps = attemps;
     public String getName() {
          return name;
     public void setName(String name) {
          this.name = name;
     public String toString()
          return this.getAttemps()+","+this.getName();
class mycompare implements Comparator
     public int compare(Object arg0, Object arg1) {
          if(arg0 instanceof player & arg1 instanceof player)
               player p1=(player)arg0;
               player p2=(player)arg1;
               int pi1=Integer.parseInt(p1.getAttemps());
               int pi2=Integer.parseInt(p2.getAttemps());
               if(pi1>pi2)
                    return 1;
               else if(pi1<pi2)
                    return -1;
               else
                    return 0;
          return 0;

Similar Messages

  • What is the relation between the two interfaces Comparable and Comparator?

    thanks.

    Comparable sorts
    on one key; Comparator
    sorts on many keysNeeds more zen... Not sure about the hyperlinks, as well.

  • Stringes and interface Comparable

    Hello
    I was wondering if you would have a 'good' solution at the following problem.
    Lets make it easy. I have a class named Farm. This farm has animals. Each of them have there own name and they have certain other characteristics. So there is a class Animal. If i have a farm, i want to find the animal in it, using its name. In each farm no two animals have the same name.
    So i'd like to use some Colletion-Class in the class Farm. If i implement in Animal the interface Comparable, i can use the "TreeMap".
    But there is one problem. I use as key the name of the animal. Assume now the farmer changes the name of the animal. Then the key in the TreeMap does NOT change with it. This is because changing a name of an animal, is the same as giving a NEW name to the animal (Strings are immutable).
    Then i thought, maybe i can use StringBuffer, but StringBuffer is final, and does not implement the interface comparable. Someone has a better idea? Are do other better collectiontypes than treemap are useful?
    Greets
    Compugreen

    Hello
    I was wondering if you would have a 'good' solution
    at the following problem.
    Lets make it easy. I have a class named Farm. This
    farm has animals. Each of them have there own name
    and they have certain other characteristics. So there
    is a class Animal. If i have a farm, i want to find
    the animal in it, using its name. In each farm no two
    animals have the same name.
    So i'd like to use some Colletion-Class in the class
    Farm. If i implement in Animal the interface
    Comparable, i can use the "TreeMap".
    But there is one problem. I use as key the name of
    the animal. Assume now the farmer changes the name
    e of the animal. Then the key in the TreeMap does NOT
    change with it. This is because changing a name of an
    animal, is the same as giving a NEW name to the
    animal (Strings are immutable).
    Then i thought, maybe i can use StringBuffer, but
    StringBuffer is final, and does not implement the
    interface comparable. Someone has a better idea? Are
    do other better collectiontypes than treemap are
    useful?
    Greets
    Compugreen
    public class Name {
       private String name;
       public Name(String name) {
          change(name);
       public void change(String newName) {
          this.name = newName;
    public class Animal {
       private Name name;
       public void changeName(String newName) {
          name.change(newName);
    public class Farm {
       private TreeMap<Name, Animal> animals = new TreeMap<Name,Animal>(); // generics notation only to express what I mean...
    }hth

  • Implementing the CompareTo(Object T) method of interface Comparable T

    Hi,
    I cannot figure out how to write implementation to compare two objects for the CompareTo method.
    I have an Employee class and a Manager class that inherits Employee and in the main method i want to sort the objects so that i can use the method binarySearch(Object[] a, Object key), originally i sorted each object in order of their salaries but i now need to be able to distinguish between a Manager object and an Employee object.

    demo:
    class Base implements Comparable<Base> {
        private String baseField;
        @Override public int compareTo(Base that) {
            return this.baseField.compareTo(that.baseField);
    class Derived extends Base {
        private String derivedField;
        @Override public int compareTo(Base that) {
            int result = super.compareTo(that);
            if (result == 0 && that instanceof Derived) {
                Derived thatThang = (Derived) that;
                result = this.derivedField.compareTo(thatThang.derivedField);
            return result;
    }Base objects are ordered by baseField. (I assume all fields will be non-null, for simplicity.) Between Derived objects with equal baseField, I order them further by derivedField.
    edit. I should mention that there are headaches that usually follow when you compare objects of different types. Suppose you have three objects:
    obj1, a Derived object with baseField = "b", derivedField = "x"
    obj2, a Base object with baseField = "b"
    obj3, a Derived object with baseField = "b", derivedField = "y"
    according to the compareTo methods, obj1 and obj2 are equal, and as well, obj2 and obj3 are equal, but obj1 and obj3 are not equal, so we do not have transitivity. ;-(

  • Sort order by custom comparable logic

    Hi All,
    Is it possible to sort the records from NamedCache.entrySet() by implementing Comparable<T> in my pojo?
    Thanks,

    user1096084 wrote:
    Thanks for your quick response.
    My requirement is to fetch objects without filter but with custom sort order and
    I couldn't find any method in QueryMap for this purpose.
    What will be result if implement Comparable interface in object?Hi,
    1. You can always use AlwaysFilter.INSTANCE for filtering.
    2. You can use a parallel aggregator to parallelly presort objects and also limit the number of objects you fetch.
    Implementing Comparable with the objects allows you to call entrySet(Filter, Comparator) with null for comparator. The method entrySet() without parameters or the entrySet(Filter) do not sort regardless of whether your objects implement comparable or not.
    Best regards,
    Robert

  • Please help...stuck with compareTo when comparing objects in ListNodes

    I'm writing a SortedLinkedList class that extends MyLinkedList that I wrote and I need to write a sort but i keep getting this error message when I try to compare two objects in the listnodes
    cannot resolve symbol method compareTo(java.lang.Object)
         Object a = get(x); //get returns an object at the listnode x(index)
         Object b = get(y);
    if(a.compareTo(b) >= 0) //Error message
    etc.....

    If you want to sort the list nodes, you can make a
    compareTo method for each node which casts its Object
    to a Comparable and calls compareTo on the arg's (arg
    is the other list node) Object.     would i put this in MySortedLinkedList class?
    public int compareTo(Object o)
              return this.compareTo((Object)o).this);
              //this is the best i can come up with so far but it doesn't help me at all

  • Userdefined Sorting the objects using comparator

    Hi All,
    I want to display the objects in a userdefined order. I have placed the code snippet below. Kindly help me on this to resolve this issue.
    public class ApplicabilityObject1 implements Comparable{
         private String str;
         public ApplicabilityObject1(String str) {
              this.str = str;
         public boolean equals(Object obj) {
              return getStr().equals(((ApplicabilityObject1)obj).getStr());
         public String toString() {
              return str;
         public String getStr() {
              return str;
         public void setStr(String str) {
              this.str = str;
         public int compareTo(Object arg0) {
              final int equal = 0;
              final int before = -1;
              final int after= 1;
              int returnvalues  = 0;
              System.out.println(this);
                                    if ("Mexico"==((ApplicabilityObject1)arg0).getStr())
                   returnvalues = -1;
              else if (((ApplicabilityObject1)arg0).getStr()== "Canada")
                   returnvalues =  0;
              else if (((ApplicabilityObject1)arg0).getStr()== "USA")
                   returnvalues = 1;
              return returnvalues;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    /*import org.apache.commons.beanutils.BeanComparator;
    import org.apache.commons.collections.comparators.FixedOrderComparator;*/
    public class SortOrder {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              APPComparator app1 = new APPComparator();
              ApplicabilityObject1 obj1 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj2 = new ApplicabilityObject1("Canada");
              ApplicabilityObject1 obj3 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj4 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj5 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj6 = new ApplicabilityObject1("USA");
              ApplicabilityObject1 obj7 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj8 = new ApplicabilityObject1("Mexico");
              ApplicabilityObject1 obj9 = new ApplicabilityObject1("Canada");
              List list = new ArrayList();
              list.add(obj1);
              list.add(obj2);
              list.add(obj3);
              list.add(obj4);
              list.add(obj5);
              list.add(obj6);
              list.add(obj7);
              list.add(obj8);
              list.add(obj9);
              Collections.sort(list, app1);
              System.err.println(list);
              System.out.println(Integer.MAX_VALUE);
    class APPComparator implements Comparator
         ApplicabilityObject1 appO = new ApplicabilityObject1("USA");
         @Override
         public int compare(Object arg0, Object arg1) {
              // TODO Auto-generated method stub
              return ((ApplicabilityObject1)arg0).compareTo(arg1);
    }I'm expecting the result in the Order of USA, CANADA, MEXICO.
    But now the above code giving the result of [USA, USA, USA, Mexico, Canada, Mexico, Mexico, Mexico, Canada]
    Kindly help me to resolve this issue.
    Thanks in advance,
    Maheswaran

    An alternative way to reduce the size of your code.
    //Un-Compiled
    ApplicabilityObject1[] appObs = {
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Canada"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("USA"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Mexico"),
      new ApplicabilityObject1("Canada")};
    List list = new ArrayList(Arrays.asList(appObs));Mel

  • Chinese Charactor sorting in List using Comparator and Collator

    I've used Collator.sort method with Locale.TRADITIONAL_CHINESE Locale to sort an ArrayList which contains a list of Chinese charactor. But it seems that the ordering is not based on stroke.
    Here is the coding for compare methods whose class implements java.util.Comparator
         public int compare(Object obj1, Object obj2){
              String string1 = (String)obj1;
              String string2 = (String)obj2;
              int compareResult = 0;
              Locale locale = locale = Locale.TRADITIONAL_CHINESE;
              Collator collator = Collator.getInstance(locale);
              compareResult = collator.compare(string1, string2);
              return compareResult;
    Could any one have exprience on it???
    Thanks,

    The resulted sequence
    "\u59cb\u6587\u65bc\u6709\u6c0f\u6f22\u7136\u7565\u7fa9\u800c\u81f3\u8a31\u8aaa\u91cd\u97f3"follows the traditional ordering of the Kangxi radicals within the limit of CJK Unified Ideographs.
    The following may be more flexible.
    import java.util.*;
    import java.io.*;
    import java.text.*;
    public class CharSort implements Comparator{
    java.text.RuleBasedCollator collator; // you can set your rules for the instance "collator"
    CharSort(){
      collator = (RuleBasedCollator)java.text.Collator.getInstance(java.util.Locale.TAIWAN);//try testing various locales
    public void doSort(String str) throws java.io.IOException{
    java.text.CollationKey[] keys = new java.text.CollationKey[str.length()];
    for(int i=0;i<keys.length;i++){
         keys[i] = collator.getCollationKey(str.substring(i,i+1));
    java.util.Arrays.sort(keys, this);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("cjk.txt"), "UTF8"));
    for(int i=0;i<keys.length;i++){
             bw.write(keys.getSourceString());
    bw.newLine();
    bw.close();
    public int compare(Object c1, Object c2) throws IllegalArgumentException{
    if((c1 instanceof CollationKey) &&(c2 instanceof CollationKey)){
    return collator.compare(((CollationKey)c1).getSourceString(), ((CollationKey)c2).getSourceString());
    }else throw new IllegalArgumentException();
    public boolean equals(Object c1, Object c2){
    if(this.compare(c1,c2)==0) return true;
    else return false;
    public static void main(String[] args) throws java.lang.Exception{
    CharSort chSort = new CharSort();
    String str = "\u81f3\u6f22\u8a31\u6c0f\u59cb\u6709\u8aaa\u6587\u7136\u91cd\u7fa9\u800c\u7565\u65bc\u97f3";
    chSort.doSort(str);

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

  • Comparable and comparator interface in java

    Hi All,
    How comparable and comparator interface works in java and when to use comparable and when to use comparator.please give me some example(code) as I am not able to understand the difference.
    Thanks
    Sumit
    Edited by: sumit7nov on May 17, 2009 4:45 AM

    Thanks,one more doubt.
    We have Collections.sort() method and we can sort any list by this method without implementing comparable or comparator interface.Then my question is when we need to implement comparable or comparator interface or when do we write our own compareTo() or compare() methods.
    Thanks
    Sumit

  • Sorting date using Comparator.

    Hi frnds,
    I have a problem sorting a date using comparator Interface. To the compare method I am passing Objects, which contains values retrieved from bean.
    I have hyperlinks for all the fields, upon clicking am able to sort all the fields except the date:
    The format of date is MM/DD/YYYY. It is sorting only taking month into consideration. I want the date to be sorted completely taking into consideration the complete date.
    Kindly help me in this regards.
    Below is the code listed:
    public int compare(Object vendoremployee1, Object vendoremployee2){
              String strSowTitle1 = ((CVendorEmployees) vendoremployee1).getSowTitle().toUpperCase();
              String strSowNum1 = ((CVendorEmployees) vendoremployee1).getSowNumber().toUpperCase();
              String lastName1 = ((CVendorEmployees) vendoremployee1).getLastName().toUpperCase();
              String strCreatedDate1 = ((CVendorEmployees) vendoremployee1).getCreatedDate().toUpperCase();
              String strSowTitle2 = ((CVendorEmployees) vendoremployee2).getSowTitle().toUpperCase();
              String strSowNum2 = ((CVendorEmployees) vendoremployee2).getSowNumber().toUpperCase();
              String lastName2 = ((CVendorEmployees) vendoremployee2).getLastName().toUpperCase();
              String strCreatedDate2 = ((CVendorEmployees) vendoremployee2).getCreatedDate().toUpperCase();
    // How do i sort
    strCreatedDate1.compareTo(strCreatedDate2);Thanks

    II am assuming that you are using either the Collections.sort() method, passing in a Vector of your objects or the Arrays.sort() method passing in an array of your objects. Either way your class definition for your object must implement Comparable. Then you have to implement the compareTo(Object o) method. Inside this method you can setup the sort any way you want. If you want the object to sort by the date member, the easiest way to accomplish the sort is to get the milliseconds from EPOC. Then you can sort either ascending or descending.
    Example code: forgive the formatting, cut and paste it into an editor
    The example has the data member as a Long object.
    Hope this is helpful.
    public int compareTo( Object o ) throws ClassCastException
              YourClassNameHere obj;
              if( o instanceof YourClassNameHere)
                   obj = (YourClassNameHere) o;
              else
                   throw new ClassCastException("Specified Object o is not of type YourClassNameHere." );
               //Only if these are not primitives
              if( this.getYourDatamember() != null && obj.getYourDatamember() != null) 
                        if(this. getYourDatamember().longValue() < obj. getYourDatamember().longValue())
                              return -1;
                        else if( this. getYourDatamember().longValue() > obj.getYourDatamember().longValue() )
                             return 1;
                        else
                             return 0;
              else if(this.getYourDatamember != null && obj.getYourDatamember() == null)
                   return -1;
              else if(this.getYourDatamember == null && obj.getYourDatamember() != null)
                   return 1;
              else
                   return 0;
         }

  • Manually Sorting Objects With compareTo

    Hello All,
    I have a quick problem I am working on. I have to implement the java compareTo interface and sort through some objects. I know this would be easier with an array, but all the comparisons of the five objects have to be done through the compareTo. For some reason, the way I am sorting is just not working... I do get output, but there is a bug in my code, and I am assured that the way I am coding is NOT the most efficient. If anyone could guide me, and help me sort the Task objects from highest to lowest based upon Complexity, it would be much appreciated.
    I will try to respond as fast as possible! I have attached the Task class and the class with main below. Thanks again!
    Task Class:
    public class Task implements Comparable
         private String taskName;
         private int priority;
         public Task (String scheduleTaskName, int importance)
              taskName = scheduleTaskName;
              priority = importance;          
         public int compareTo(Object obj)
              Task comparedTask = (Task)obj;
              int comparedTaskPriority = comparedTask.getPriority();
              if (priority < comparedTaskPriority)
                   return -1;
              else if (priority > comparedTaskPriority)
                   return 1;
              else
                   return 0;
         public int getPriority()
              return priority;
         public Task copySelf()
              return this;
         public String toString()
              String result = "P: " + priority + "\t " + taskName;
              return result;
    }Schedule Class:
    //This is the driver class for Task / Comparable implementation.
    public class Schedule
         public static Task task1 = new Task("", 0);
         public static Task task2 = new Task("", 0);
         public static Task task3 = new Task("", 0);
         public static Task task4 = new Task("", 0);
         public static Task task5 = new Task("", 0);
         public static int sortHighest = 0;
         public static void main(String[]args)
              EasyReader console = new EasyReader(System.in);
              //Declare all the variables, but values will be updated as needed.
              //NOTE: These can NEVER be null or there will be errors in the compare!
              System.out.println("Welcome to the complexity scheduler program!");
              System.out.println("We can schedule up to 5 things per day, and rate how complex they are!");
              System.out.println("How many things would you like to schedule today?");
              int numberOfTasks = console.intInput();
              while (numberOfTasks > 5 || numberOfTasks < 1) //Check how valid the input is.
                   System.out.println("We cannot do this many tasks... Please enter a valid number [1-5]:");
                   numberOfTasks = console.intInput();
              System.out.println();
              //Read in all the tasks in an orderly manner.
              for (int x=1; x<=numberOfTasks; x++)
                   System.out.println("Task number " + x + ":");
                   System.out.println("Please enter the task name:");
                   String taskBuffer = console.stringInput();
                   System.out.println("How complex is this task to you?");
                   int importanceBuffer = console.intInput();
                   //Validate the entry that way the sorting will work.
                   while (importanceBuffer <= 0)
                        System.out.println("Please enter a valid importance that is greater than zero! :");
                        importanceBuffer = console.intInput();
                   if(x == 1)
                        task1 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 2)
                        task2 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 3)
                        task3 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 4)
                        task4 = new Task(taskBuffer, importanceBuffer);
                   else if (x == 5)
                        task5 = new Task(taskBuffer, importanceBuffer);
                   System.out.println();
              System.out.println("Thank you for entering in your tasks.");
              System.out.println("Are you ready for them to be sorted and shown? [Y/n]");
              String userChoice = console.stringInput();
              //And here is where we start to sort it.
              if (userChoice.equalsIgnoreCase("y"))
                   System.out.println();
                   sortHighest = numberOfTasks+1;
                   for (int y=1; y <= numberOfTasks; y++)
                        Task temporaryTask;
                        if(y==1)
                             temporaryTask = sortTask(task1);
                        else if (y==2)
                             temporaryTask = sortTask(task2);
                        else if (y==3)
                             temporaryTask = sortTask(task3);
                        else if (y==4)
                             temporaryTask = sortTask(task4);
                        else
                             temporaryTask = sortTask(task5);
                        System.out.println(temporaryTask);
         public static Task sortTask(Task input)
              Task result = input;
              //And the sort goes like this...
              if (result.compareTo(task1) < 0 && task1.getPriority() < sortHighest)
                   result = task1;
              if (result.compareTo(task2) < 0 && task2.getPriority() < sortHighest)
                   result = task2;
              if (result.compareTo(task3) < 0 && task3.getPriority() < sortHighest)
                   result = task3;
              if (result.compareTo(task4) < 0 && task4.getPriority() < sortHighest)
                   result = task4;
              if (result.compareTo(task5) < 0 && task5.getPriority() < sortHighest)
                   result = task5;
              sortHighest = result.getPriority() - 1;
              return result;
    }

    They can be sorted and stored in seperate Task
    objects.. Okay, stop and think about this for a minute.
    The usual way to sort is something like:Arrays.sort(someArray);
    or
    Collections.sort(someList);The sort routine can sort any number of objects--however many are in the list or array.
    Now, your bubblesort method--like the core API's sort methods--will call your compareTo methods on pairs of your objects.
    What will be the signature of your bubblesort method? Will it sort a fixed number of objects?
    bubbleSort(task1, task2, task3, task4, task5)Note that it's impossible for this to even work in Java, because those references will be passed by value. There could not be a separate sort method. You'd have to implement your sort routine inline in the method where they're defined, or they'd have to be member variables. Either way, it's nonsense.
    Not being able to use arrays or lists is a ridiculous requirement. I'm almost certain you misunderstood. Perhaps you're not allowed to use the Arrays.sort method.
    If your teacher really said you can't use arrays, he has no business teaching this class.

  • Insertion sorts and comparable

    HI guys. I need to refresh my memory for these two things, Insertion sorts and comparable.
    I don't quite understand what is the different between insertion sorts and selection sorts.
    And secondary, comparable. What is it for? How does it work? Here is the sample code. All I see is the use of it to call the compareTo method.
    public static void main (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--;
    }//end while
    objects[] = key;
    }//end for
    Thanks a lot.

    HI guys. I need to refresh my memory for these two
    things, Insertion sorts and comparable.
    I don't quite understand what is the different between
    insertion sorts and selection sorts. They are different sorting algorithms.
    (As you understand, I don't remember much either :) )
    You're probably best off by finding a book about it.
    And secondary, comparable. What is it for? How does it
    work? Here is the sample code. All I see is the use of
    it to call the compareTo method.Comparable is an interface that declares the compareTo-method. By using that general method you can write a general sorting method that are independent on what objects are being sorted and how they are being sorted, as long as they implement Comparable.

  • The Comparable interface

    Hi,
    i am writing a class that i would like to implement the interface Comparable. The java api says that the class must therefore have a method called "compareTo" which returns an int, for less than, equal to or greater than.
    My method does this, however the int it returns is actually meaningful as well, therefore the int that is returned is not just -1, 0 or 1 but other numbers... yet still corressponding to less than, equal to or greater than.
    Does this mean my class properly implements Comparable or does it HAVE to be -1, 0 or 1?
    Edited by: creman42 on Feb 3, 2008 10:30 PM

    creman42 wrote:
    no, but there was something about this sentence that i was slightly unsure about;
    "In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.) "They're saying that the return function of the sgn function will be -1, 0, or -1, and that by using such a function, you can determine the correctness of your compareTo method. Basically they're just being precise about how compareTo has to behave.
    My mistake for posting here, i should have posted in the New to Java board, this is obviously far too stupid a question, my sincere apologies It's not a stupid question but it's poorly asked. If the stuff about the sgn function was what confused you, then you should have mentioned it at the outset.

  • Quicksort using Comparable can sort out negative value well !!

    man , i have waste another day try to solve this logic problem. It was not easy as what i thought. The Qsort method which i found it on the net and i apply it into my java code .. i do understand his code well , however the result does not sort out well especially negative number or if there is there are small number at the end of the array. Below are some result which i compile .Hope someone can help me , i going crazy soon.
    sample 1:
    Before Soft()
    [93, 50, 34, 24, -48, 27, 45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -37, -48, -71, -95, 11, 16, 2, 24, 27, 34, 45, 50, 51, 60, 93]
    sample 2:
    Before Soft()
    [-93, 50, -34, -24, 48, -27, -45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -24, -27, -34, -37, -45, -71, -93, -95, 11, 16, 2, 48, 50, 51, 60]
    sample 3 ==> this one is correct ;-)
    Before Soft()
    [93, 50, 34, 24, 48, 27, 45, 11, 60, 51, 95, 16, 12, 71, 37, 20]
    After Soft()
    [11, 12, 16, 20, 24, 27, 34, 37, 45, 48, 50, 51, 60, 71, 93, 95]
    import java.util.*;
    import java.lang.Comparable;
    public class QuickSort {
    // static Comparable [] array;
    public QuickSort(){}
    public static void main ( String [] args){
              QuickSort qs =new QuickSort ( );
              Object [] test = new Object [16];
              test[0]="93";
              test[1]="50";
              test[2]="34";
              test[3]="24";
              test[4]="-48";
              test[5]="27";
              test[6]="45";
              test[7]="11";
              test[8]="60";
              test[9]="51";
              test[10]="-95";
              test[11]="16";
              test[12]="-12";
              test[13]="-71";
              test[14]="-37";
              test[15]="2";
              for (int i=0;i<test.length;i++)
              System.out.println(test);
              System.out.println();
    /* Copy the value from the Object [ ]test into Comparable [] array. /*
    Comparable [] array = new Comparable [test.length];
    for(int i=0;i<array.length;i++)
         array [i]=(Comparable) test[i];          
         System.out.println(array[i]); //test if the value is the same as the test Object //
    System.out.println("Before Soft()");
    System.out.println(Arrays.asList(array));
    qs.sort(array); //call sort method to sort the array
    System.out.println("After Soft()");
         System.out.println(Arrays.asList(array));
    * Sorts the array of Comparable objects using the QuickSort algorithm.
    * @param comparable an array of java.lang.Comparable objects
    public void sort(Comparable comparable[]) {
    QSort(comparable, 0, comparable.length - 1);
    * @param comparable an array of java.lang.Comparable objects
    * @param lowInt int containing lowest index of array partition
    * @param highInt int containing highest index of array partition
    static void QSort(Comparable comparable[], int lowInt, int highInt) {
    int low = lowInt;
    int high = highInt;
    Comparable middle;
    // The partion to be sorted is split into two separate sections which are
    // sorted individually. This is done by arbitrarily establishing the middle
    // object as the starting point.
    if (highInt > lowInt) {
    middle = comparable[(lowInt + highInt) / 2];
    // Increment low and decrement high until they cross.
    while (low <= high) {
    // Increment low until low >= highInt or the comparison between
    // middle and comparable[low] no longer yields -1 (ie comparable[low]
    // is >= middle).
    while (low < highInt && (comparable[low].compareTo(middle) < 0)) {
    ++low;
    // Decrement high until high <= lowInt or the comparison between
    // middle and comparable[high] no longer yields 1 (ie comparable[high]
    // is <= middle).
    while (high > lowInt && (comparable[high].compareTo(middle) > 0 )) {
    --high;
    /*switch over */
    if (low <= high) {
    Comparable obj;
    obj = comparable[low];
    comparable[low] = comparable[high];
    comparable[high] = obj;
    ++low;
    --high;
    if (lowInt < high) {
    QSort(comparable, lowInt, high);
    if (low < highInt) {
    QSort(comparable, low, highInt);

    the problem is solve after cos i cast a string variable into the object comparable. The problem is solve after i use cast Integer into the object.
    regards
    st

Maybe you are looking for