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);

Similar Messages

  • SSRS reporting with sharepoint list using Distinct and Multivalue parameters

    i want create ssrs report with sharepoint list using ms-vs(2008). i want create Distinct multivalue parameters by using CAML query. There is any way we put CAML query where we use Distinct keyword and IN clause in CAML query... i hope all experts will
    understand my poor English... sorry for poor English.. plz help me

    Hi AsifMehmood,
    Per my understanding you have create an SSRS report with SharePoint list, now you don’t know to create the distinct parameters by using CAML query,  right?
    For the CAML language doesn’t have any reserved word (or tag) to set this particular filter to remove duplicate results, but we can use the custom code to do this function. I have tested on my local environment and we can do that by create one hidden parameter(Param1)
    to get all the values from the fields which will  add the filter and then create another parameter(Param2) to get the distinct values based on the Param1, we use the custom code to do the deduplication.
    Step by Steps information in below thread for your reference to create the parameters and the custom code:
    "How to get distinct values of sharepoint column using SSRS"
    Other similar thread for your reference:
    https://audministrator.wordpress.com/2014/02/17/sharepoint-list-add-distinct-parameter-value/
    If your problem still exists, please feel free to ask and also try to provide us more details information.
    Regards
    Vicky Liu

  • TUTORIAL: NSDictionary Sorting By Value using NSNumbers and NSStrings

    Even though this may be a basic topic for some, I struggled with it as usual, so here's what I learned.
    Very short, a few screen captures, and a half a page of text total.
    As usual shows the source code, and I included the project.
    This is what I learned today while hanging around the forum.
    Got some great help, and would particularly like to thank RayNewbie for getting me on the right track, and etresoft who tried to help me with the hybrid bindings problem that was eventually solved by xnav, and K T as well for trying to get me on the right path with my myriad of messages...
    ABOUT THE DICTIONARIES :
    http://www.journey-of-flight.com/bhxcode/how-to/0105_Sort_Array_ByValue/index.php
    I really am grateful to those who take the time to help.
    Thank You...
    Bill Hernandez
    Plano, Texas

    When I first created the project I was going to use arrays, and as it turned out I used arrays, and a couple of dictionaries, one original and one sorted with the results.
    I created a new project, and took some of the screen captures again.
    The corrected project, that reflects the correct topic is :
    http://www.journey-of-flight.com/bhxcode/how-to/0105_Sort_Dictionary_ByValue/index.php
    Sorry for the goof...
    Bill Hernandez
    Plano, Texas

  • Highscore list using Flash and PHP

    Hi,
    I want to make a highscorelist using AS3 and PHP(MySQL).
    I cant find a good tutorial on internet how to make something like that but I got this so far:
    import fl.controls.TextInput;
    import fl.controls.TextArea;
    var variables:URLVariables = new URLVariables();
    variables.name = "Wil";
    variables.final = 2000;
    var request:URLRequest = new URLRequest();
    ////insert in the location of the php script ////////////////
    request.url = "http://www.justenter.nl/script.php";
    request.data = variables;
    var loader:URLLoader = new URLLoader();
    loader.load(request); //sends the request
    //when the request is done loading, it goes to the completeWriting function
    loader.addEventListener(Event.COMPLETE, completeWriting);
    function completeWriting(event:Event):void {
        var writingCompleted:TextField = new TextField;
        writingCompleted.autoSize = "center";
        writingCompleted.x =200;
        writingCompleted.y= 200;
        writingCompleted.text = event.target.data;
        addChild(writingCompleted);
    He is sending the score and name to the database but he is doing that when i press ctrl-enter. He is sending the data I have given in:
    variables.name = "Wil";
    variables.final = 2000;
    I want a input textfield and a button. And When I fill in my name in the input textfield he send it to the database when I press the button.
    Is there someone that can help me out?
    Tnx

    import fl.controls.TextInput;
    import fl.controls.TextArea;
    var variables:URLVariables = new URLVariables();
    //variables.name = "Wil";
    //variables.final = 2000;
    var request:URLRequest = new URLRequest();
    ////insert in the location of the php script ////////////////
    request.url = "http://www.justenter.nl/script.php";
    request.data = variables;
    var loader:URLLoader = new URLLoader();
    submitBtn.addEventListener(MouseEvent.CLICK,submitF);  // where submitBtn is your button
    function submitF(e:Event){
    variables.name=nameTF.text; // where nameTF is your input texfield
    variables.final = score;  // where score is the variable you use to tally user score
    loader.load(request); //sends the request
    //when the request is done loading, it goes to the completeWriting function
    loader.addEventListener(Event.COMPLETE, completeWriting);
    function completeWriting(event:Event):void {
        var writingCompleted:TextField = new TextField;
        writingCompleted.autoSize = "center";
        writingCompleted.x =200;
        writingCompleted.y= 200;
        writingCompleted.text = event.target.data;
        addChild(writingCompleted);

  • 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

  • How to use Compare and Swap (CAS) atomic function(Solaris specific) in C

    Hi,
    I have found cas32() atomic function in (solaris 10) </usr/include/sys/atomic.h> (and also there is another atomic.h header file in </usr/include/atomic.h> but this header file does not have any cas32() function declarations) the declaration of cas32 in <sys/atomic.h>
    is as follows
    extern uint32_t cas32(uint32_t *target, uint32_t cmp, uint32_t newval);
    extern ulong_t caslong(ulong_t *target, ulong_t cmp, ulong_t newval);
    extern uint64_t cas64(uint64_t *target, uint64_t cmp, uint64_t newval);
    extern void casptr(void target, void cmp, void newval);
    extern uint8_t cas8(uint8_t *target, uint8_t cmp, uint8_t newval);
    But the problem is when iam using these functions in c programs and compiling
    using gcc it is showing the following error.
    Undefined first referenced
    symbol in file
    cas32 /var/tmp//ccQcsnev.o
    And if i use the function other than cas32 group of instruction
    such as atomic_or_uint()
    whose declaration is extern void atomic_or_uint(uint_t *target, uint_t bits);
    in <sys/atomic.h> it is giving no error where as for CAS32 it showing as undefined symbol.Why it is giving like that we are not able to know.Is it the case that CAS32 instruction only available in Kernel mode and not available to user mode.Please inform us if anyone knows how to use cas32() instruction in the user C programs.As this is usefull for writing Nonblocking versions of stacks and Queues.Is there any way to write
    our own atomic functions?
    Rama

    You are trying to use the old kernel-only CAS functions, use the correct ones like:
    atomic_cas_32.
    DS

  • Line details sort order when using Pick and Pack

    Hi,
    A customer of mine recently complained (very small complain) that when he used "Per date" as a sort when using Pick & Pack, that the line details where not grouped together by Sales Order Number.
    Example:
    2008/11/23   SO1001 - Line 1
    2008/11/23   SO1013 - Line 3
    2008/11/23   SO1001 - Line 2
    2008/11/23   SO1001 - Line 4
    2008/11/23   SO1021 - Line 1
    2008/11/23   SO1001 - Line 5
    etc...
    Is there a way to sort records on two columns instead of just one? or would there be another workaround this issue?
    Thanks
    Charles

    I think I found my answer, sorting data using the Data/Sort feature allows for sorting on multiple columns.

  • Dynamic Entity Member Lists using UD1 and UD2

    Hello fellow HFM gurus:
    I have created dynamic member lists to get all members of the entity dimension that have a UD1 or UD2 member as specified in the script.
    THe member lists all appear in HFM, but when I try to select them, I get a run-time error. I am trying to select them in the member selection of a data form (in the same drop down with the different system member lists for entiites, like hierarchy, descendants, etc.).
    I believe this is the standard syntax. Please let me know if something is wrong with it.
    ElseIf HS.Dimension = "Entity" Then
    If HS.MemberListID = 1 Then
    ELi=Hs.Entity.List(",")
    For i = Lbound(ELi) to Ubound(ELi)
    If HS.Entity.IsBase("",ELi(i)) = TRUE Then
    If (StrComp(Hs.Entity.UD1(ELi(i)),"DD",vbTextCompare)=0) Then
    Hs.AddEntityToList "",ELi(i)     
    End If
    End If     
    Next
    End if     
    Error in HFM:
    Invalid member selection. Error executing VBScript Microsoft VBScript runtime error, Line 475:Wrong number of arguments or invalid property assignment: 'HS.Entity.List'.Error executing VBScript 0.Error Reference Number: {9A7697E2-75AE-4A06-9A34-B45D58022984};User Name: mark.d.smith@Native DirectoryNum: 0x80042fc2;Type: 1;DTime: 9/10/2012 5:51:16 PM;Svr: VMHODDLPHP4;File: CHsvScriptEngine.cpp;Line: 392;Ver: 11.1.2.1.103.3505;Num: 0x80042fc2;Type: 0;DTime: 9/10/2012 5:51:16 PM;Svr: VMHODDLPHP4;File: CHsvDSMemberLists.cpp;Line: 2722;Ver: 11.1.2.1.103.3505;Num: 0x80042fc2;Type: 0;DTime: 9/10/2012 5:51:16 PM;Svr: VMHODDLPHP4;File: CommonMetadataInternal.cpp;Line: 461;Ver: 11.1.2.1.103.3505;Num: 0x80042fc2;Type: 0;DTime: 9/10/2012 5:51:16 PM;Svr: VMHODDLPHP4;File: CHsvEntities.cpp;Line: 338;Ver: 11.1.2.1.103.3505;Num: 0x80042fc2;Type: 1;DTime: 9/10/2012 5:51:16 PM;Svr: VMHODDLPHP4;File: CCommonDimension.cpp;Line: 1015;Ver: 11.1.2.1.103.3505;

    Hi Mark,
    Please check the double quotes after Entity.List. It should be "","".
    Regards,
    S

  • Need help in using Comparator

    hi,
    I have a list of objects in that there is a field called lastModifiedDate.
    I have to sort the list on the basis of this filed.
    I m trying to sort the list using Comparator, also converting the date field in long. But I m getting back the list, in that entries are sorted but duplicates though the original list is having unique values.
    I have used the code as follows:
    public int compare(Object arg0, Object arg1) {
    if (((((ComparatorEntity) arg0).getDate()) - (((ComparatorEntity) arg1).getDate())) < 0) {
         return 1 ;
    else {
         return 0 ;
    please help me
    Thanx in advance.
    Abhishek

    Well, your Comparator is wrong because it never returns -1. That won't cause it to insert additional elements though. I'd suggest you print both the list and its size, both before and after sorting.
    Also, if you put the -1 return value in following the pattern you've started, the list will be sorted in reverse order. That may be what you want, but I thought I'd point it out in case it's not.
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • 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;
         }

  • 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

  • Comparable and Comparator Interface - Collections

    Hi All
    Please let me know when to use Comparable interface and Comparator interface. ?
    Any sort of information is highly appreciable .
    Matt

    Matt wrote:
    @ jverd      
    So, when you googled, and found tutorials, and worked through those tutorials, and read the javadocs for those classes, what in particular did you not understand?If everything would work like that what will be the use of forums like this , It does work like that, for people who aren't lazy. The use of these forums, as indicated by my first reply, is among other things, when you've done your own research, as you should do, and run into something you don't understand.
    so dont try to be smart :(Maybe you should try to be smarter.
    Lets try not to abuse the forum with exchanges like this. The only abuse so far has been you expecting the forum to be a substitute for doing your own research.
    I know how to use Comparable and Comparator but dont know when to use these in a real time application.That statement says nothing about your problem. The only information it carries is that you don't know what the term "real time" means.

  • Whats the difference between comparable and comparator?

    whats the difference between comparable and comparator?
    when must i use comparable, and when must i use comparator?

    whats the difference between comparable and
    comparator?Comparable is from the java.lang package, Comparator from java.util.
    when must i use comparable, and when must i use
    comparator?Here's a tutorial on both:
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

  • Sorting array list

    can u please give me the source code for:
    sorting array list for ascending and descending order

    You already have the source code.

  • Sort array list and using comparable

    With the following code I would like to setup a score object for the current player.
    Change it to a string(Is it correct to say parse it to a string type)
    Then add it to the arraylist.
    So I can sort the array list according to the string size.
    That's why I have the variables in that order.
    So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
    Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
    Is the string idea I am trying here possible? is it practical or should I use comparable?
    I have looked at comparable, but I don't get it.
    Will my Score class implement comparable. I am looking at an example with the following code.
    Employee.java
    public class Employee implements Comparable {
        int EmpID;
        String Ename;
        double Sal;
        static int i;
        public Employee() {
            EmpID = i++;
            Ename = "dont know";
            Sal = 0.0;
        public Employee(String ename, double sal) {
            EmpID = i++;
            Ename = ename;
            Sal = sal;
        public String toString() {
            return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
        public int compareTo(Object o1) {
            if (this.Sal == ((Employee) o1).Sal)
                return 0;
            else if ((this.Sal) > ((Employee) o1).Sal)
                return 1;
            else
                return -1;
    ComparableDemo.java
    import java.util.*;
    public class ComparableDemo{
        public static void main(String[] args) {
            List ts1 = new ArrayList();
            ts1.add(new Employee ("Tom",40000.00));
            ts1.add(new Employee ("Harry",20000.00));
            ts1.add(new Employee ("Maggie",50000.00));
            ts1.add(new Employee ("Chris",70000.00));
            Collections.sort(ts1);
            Iterator itr = ts1.iterator();
            while(itr.hasNext()){
                Object element = itr.next();
                System.out.println(element + "\n");
    }The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
    What if I only use currentScore in a loop which loops every time the player restarts?
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
    Thanks in advance.
    Edited by: Implode on Oct 7, 2009 9:27 AM
    Edited by: Implode on Oct 7, 2009 9:28 AM

    jverd wrote:
    Implode wrote:
    I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
    You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
    The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
    For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
    Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
    Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
    Once we reach the end of the list, the item in position 1 is the "smallest".
    Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
    Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
    massive help
    I understand that now, but I am clueless on how to implement it.
    Edited by: Implode on Oct 7, 2009 10:56 AM

Maybe you are looking for

  • Premiere being slow and unstable

    Hello everyone! However I've been using Premiere for quite a few years I've never experienced this issue before. Premiere pro is being unstable, inaccurate and slow. Playback is just not working unless I render the sequence. Clicking on the timeline

  • TS1559 can i connect  my ipod to my ps3?

    can i connect my ipod to my ps3?

  • Automator Workflow Copying Files

    I want to create an Automator workflow that copy items to a destination folder but ignores files that already exist in the destination. I begin having trouble at the "Copy Finder Items" action where the only options are to replace existing files or c

  • Movieclip buttons actionscript errors

    Hi, I have tried using this type of button for the first time and also ActionScript. I have made a movie clip with _up and _over states and it works. But the onRelease is doing two strange things. Firstly, If I click on a button it will go to the pag

  • Artwork not syncing fix?

    Using iTunes 8 / iPhone 3G 2.1 Some art work gets lost in syncing w/ iTunes. I found if I uncheck "sync music" in iTunes hit "Apply" then recheck "sync music" they are all back untill I resync againg a couple of times the the same ones dissappear. AP