Sorting Objects Using Comparator

Alright,
I have an ArrayList of Audio Objects:
public Audio(String title, String author, String genre, int year)
          this.title = title;
          this.author = author;
          this.genre = genre;
          this.year = year;
     }Now, according to User Input you can sort the Objects either by Title Ascending/Descending, Author Ascend/Descend etc.
Now I am at a loss to how to define the actual Comparator...
public int compare(Audio a, Audio b)
          if(a.getTitle().compareTo(b.getTitle()) < 0)
               return -1;
          if(a.getTitle().compareTo(b.getTitle()) > 0)
               return 1;
          return 0;
     }(Is that correct?)
Would I need a separate Comparator interface for each sort? Then all I need is to use the Collections.sort() method yes?
I appreciate any comments and feedback. Thank you.

Now I am at a loss to how to define the actual Comparator...Should work but you can simplfy the coding and just use:
return a.getTitle().compareTo(b.getTitle());
Would I need a separate Comparator interface for each sort? Yes.
Then all I need is to use the Collections.sort() method Yes
I appreciate any comments and feedbackWhat I fail to understand is why you wouldn't create a simple test class to see if you understand what you are doing. Why post a question and wait hours hoping someone answers the question? We learn by our successes and mistakes.
Generally, try something first, then if it doesn't work ask a question. That way you have the code to post so we can see what you might be doing wrong.
Here is a simple demo of what you are attempting to do:
http://forum.java.sun.com/thread.jspa?forumID=31&threadID=598401

Similar Messages

  • Help... How to sort booleans using Comparable?

    Hi friends...
    I need to sort booleans using Comparable... The problem is, the compiler tells me it needs Objects, not booleans...
    Does somebody has an idea what to do, knowing I must use Comparable?
    ThanX for your help...

    Hi Abuse...
    I know it sounds a bit dumb... :-)
    I need to make two different blocks of lines, and with boolean rendered as checkboxes, I can change the size of these blocks by getting some lines true, other false. By using some columns of checkboxes, you can really do great sorting stuff...
    C ya...

  • List with multiple objects using Comparator

    Hi,
    I have a comparator to sort the fields of 2 objects. I have a resultlist which contains the CustomerAddressVO which contains the properties of both
    Customer and Address entities List resultList<CustomerAddressVO>.
    This CustomerAddressVO.java in turn have
    private long id
    private Customer customer;
    private Address address;
    Where Customer.java
    will have properties of customer
    Where Address.java
    will have properties of address
    Now i need to use the comparator for customer.getName() asc and address.id() desc, as i have mentioned the resultList doesn't directly contain this object as it contains CustomerAddressVO which in turn have those two object Customer and Address. Hence unless you iterate the list and retrieve the respective objects (customer, address) you cannot do the sorting through comparator. In such case how we can go about it. If you iterate the list also how we can pass the respective object to the compare() ? And more importantly we need to sort the columns of 2 different entites? Please clarify how we can go about it?
    Thanks.

    You can still do the sorting through a Comparator
    The compare method should take
    public int compare(CustomerAddressVO o1, CustomerAddressVO o2) { //..so you can then do
    01.getCustomer().getName();
    //and
    o1.getAddress().getId() together with relevant null checks

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

  • 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

  • LinkedList, sort method with Comparable class

    I have created my own LinkedList class; named Linked (empty list) and LinkedNode. One of the method is sort() that use Comparable class. My problem is when I use my Linked class in my Library class (that uses Linked<Book> list = new Linked<Book>();) I face problem and the methods throw excpetion, and I discovered that this excpetion is from Comparable class.
    The sort() method in Linked class:
    public Linked<E> sort(){
              Linked<E> newList = new Linked<E>();
              System.out.println("Here is your prob");
              Comparable h = (Comparable)head;// head +compareTo
              System.out.println("Here is your prob");
              Linked<E> less = new Linked<E>();
              Linked<E> more = new Linked<E>();
              for(Linked<E> l = tail; !l.empty(); l=l.tail() ){
                   if(h.compareTo(l.head())>0)
                        less=less.add(l.head());
                   else
                        more=more.add(l.head());
              less=less.sort();
              more=more.sort();
              newList=less.join(more.add(head));
              return newList;
         }The sortCollection method in Library class:
    public void sortCollection()throws NullPointerException{
    list.sort();  } Also, I want to do my own Comparable class that switch between different sort modes.
    Hope my question is clear.
    Regards,

    The exception is
    java.lang.ClassCastException: Library.Book
         at Library.LinkedNode.sort(LinkedNode.java:58)
         at Library.BookLibrary.sortCollection(BookLibrary.java:145)
         at GUI.Projecc.actionPerformed(Projecc.java:351)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Sorting a vector of objects using attribute of object class as comparator

    i would like to sort a vector of objects using an attribute of object class as comparator. let me explain, i'm not sure to be clear.
    class MyObject{
    String name;
    int value1;
    int value2;
    int value3;
    i've got a Vector made of MyObject objects, and i would sort it, for instance, into ascending numerical order of the value1 attribute. Could someone help me please?
    KINSKI.

    Vector does not implement a sorted collection, so you can't use a Comparator. Why don't you use a TreeSet? Then you couldclass MyObject
      String name;
      int value1;
      int value2;
      int value3;
      // Override equals() in this class to match what our comparator does
      boolean equals (Object cand)
        // Verify comparability; this will also allow subclasses.
        if (cand !instanceof MyObject)
          throw new ClassCastException();
        return value1 = cand.value1;
      // Provide the comparator for this class. Make it static; instance not required
      static Comparator getComparator ()
        // Return this class's comparator
        return new MyClassComparator();
      // Define a comparator for this class
      private static class MyClassComparator implements Comparator
        compare (Object cand1, Object cand2)
          // Verify comparability; this will also allow subclasses.
          if ((cand1 !instanceof MyObject) || (cand2 !instanceof MyObject))
            throw new ClassCastException();
          // Compare. Less-than return -1
          if ((MyObject) cand1.value1 < (MyObject) cand2.value1))
            return -1;
          // Greater-than return 1
          else if ((MyObject) cand1.value1 > (MyObject) cand2.value1))
            return 1;
          // Equal-to return 0.
          else
            return 0;
    }then just pass MyObject.getComparator() (you don't need to create an instance) when you create the TreeSet.

  • 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]

  • 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

  • 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

  • Using Comparator to sort an array

    I didn't undersatnd why a comparator is used for sorting an arry in ascending order
    For descending also i didn't understand the logic it follows
    I have a program which works for both asc and desc using comparator
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    can anyone explain
    1 why do we are passing an object of Ascend class(code was there in above program) to Arrays.sort() method
    2. what will be retruned by that object
    3 why do we are passing an object of Descend class(code was there in above program) to Arrays.sort() method
    4. what will be retruned by that object
    5 We can sort the array in ascending simply by using Arrays.sort(arr) method directly, then what was usage of Ascend class
    If I am wrong in understating the code of the above pls correct me and tell me the actual usage of Comparator<T> interfance and its method compare()
    Pls....

    camickr wrote:
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.am sorry!! pls find the code and try to execute it. It works fine in sorting
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    Can u explain the below
    what happens actually when Arrays.sort(arr,new Descend() ) is executed

  • I can't seem to get individual elements when comparing 2 arrays using Compare-Object

    My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
    servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
    but I want to provide all the information, hopefully making it easier for you to help me :)
    Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
    Total entries (arrMasterServers): 245
    Total entries (arrNewServers): 244
    Comparing new against master
    There are 1 differences.
    InputObject SideIndicator
    @{Agent= Virtual Server in vCenterServer; Backupse... <=
    What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
    right, building the array right, or using Compare-Object correctly.
    Thank you!
    Sample opening lines from the report
    " CommCells > myComCellServer (Reports) >"
    " myComCellServer -"
    " 30 day SLA"
    CommCell Details
    " Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
    " myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
    " myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
    Entire script
    # things to add
    # what date was server entered in list
    # how many days has server been on list
    # add temp.status = pre-existing, new, removed from list
    # copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
    ## 20150114 Created script ##
    #declare global variables
    $global:arrNewServers = @()
    $global:arrMasterServers = @()
    $global:countNewServers = 1
    function Get-NewServers
    Param($path)
    Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
    write-host "If not original report, break out of script"
    Write-Host ""
    #skip 5 to include headers, 6 for no headers
    (Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
    $sourceNewServers = get-content -path $path
    $global:countNewServers = 1
    foreach ($line in $sourceNewServers)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
    $temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
    $temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
    $temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
    #write temp object to array
    $global:arrNewServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countNewServers ++
    Write-Host ""
    $exportYN = Read-Host "Do you want to export new servers to new master list?"
    $exportYN = $exportYN.ToUpper()
    if ($exportYN -eq "Y")
    $exportPath = Read-Host "Enter full path to export to"
    Write-Host "Exporting to $($exportPath)"
    foreach ($server in $arrNewServers)
    $newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
    Add-Content -Path $exportPath -Value $newtext
    function Get-MasterServers
    Param($path)
    $sourceMaster = get-content -path $path
    $global:countMasterServers = 1
    foreach ($line in $sourceMaster)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0]
    $temp.Agent = $tempLine[1]
    $temp.Backupset = $tempLine[2]
    $temp.Reason = $tempLine[3]
    #write temp object to array
    $global:arrMasterServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countMasterServers ++
    function Compare-NewAgainstMaster
    Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    Write-Host "Total entries (arrNewServers): $($countNewServers)"
    Write-Host "Comparing new against master"
    #Compare-Object $arrMasterServers $arrNewServers
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Write-Host "There are $($arrDifferent.Count) differences."
    foreach ($item in $arrDifferent)
    $item
    ## BEGIN CODE ##
    cls
    $getMasterServersYN = Read-Host "Do you want to get master servers?"
    $getMasterServersYN = $getMasterServersYN.ToUpper()
    if ($getMasterServersYN -eq "Y")
    $filePathMaster = Read-Host "Enter full path and file name to master server list"
    $temp = Test-Path $filePathMaster
    if ($temp -eq $false)
    Read-Host "File not found ($($filePathMaster)), press any key to exit script"
    exit
    Get-MasterServers -path $filePathMaster
    $getNewServersYN = Read-Host "Do you want to get new servers?"
    $getNewServersYN = $getNewServersYN.ToUpper()
    if ($getNewServersYN -eq "Y")
    $filePathNewServers = Read-Host "Enter full path and file name to new server list"
    $temp = Test-Path $filePathNewServers
    if ($temp -eq $false)
    Read-Host "File not found ($($filePath)), press any key to exit script"
    exit
    Get-NewServers -path $filePathNewServers
    #$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrNewServers): $($countNewServers)"
    #Write-Host ""
    #$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    #Write-Host ""
    Compare-NewAgainstMaster

    do not do this:
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Try this:
    $arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
    ¯\_(ツ)_/¯
    This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
    in a little more detail. Thank you very much!
    Yes - this is the way PowerShell works.  You do not need to write so much code once you understand what PS can and is doing.
    ¯\_(ツ)_/¯

  • 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.

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • Why do vector objects use a different GUI to set colours?

    While teaching Photoshop in a class of mine, I noticed that in CS6 vector objects's colours remain unaffected by the main colour controls, and we have to switch to the object selection tool to display the colour controls in the properties bar.
    Now, this feels very, very disjointed - why would one introduce such a disconnect in the overall user interface? Why not just use the ordinary colour controls? I mean, trying to pick up the colour from a bitmap layer for a vector object takes five steps now: select object with object selection tool, click on the fill button in the properties bar, click on the colour picker, then we can pick up a colour from the image, anc finally click to confirm. And the colour change only gets applied after clicking "okay". No realtime feedback. Have to repeat the last three steps again and again to test for different colours.
    Wow. Just... Wow. :-(
    The Colour swatch palette does not work either with vector objects. Nor the eye dropper tool! Just plain silly, if you ask me.
    Quite a bad workflow, or am I missing something here?
    I compare this to Photoline, where the overall colour controls govern all types of objects, including vector layers and bitmap layers the same way, and with instant feedback. Photoshop CS6's colour picking workflow for vector objects looks extremely convoluted compared.
    Has this workflow been improved at all in Photoshop CC?

    @ JJMack: I used Photoshop in a professional manner since version 3, so I am sort of privy to its overall development throughout the years. ;-)
    My intention is not to start a comparison between Photoline and Photoshop - both have their caveats and benefits. I stopped using Photoshop 9 months ago and switched to Photoline, and on overall, I much prefer PL's workflow now for image editing and compositing. (Comparing Elements with PL is not really a fair fight - PL's feature set, aside from the 3d, scripting, and video components, is 95% feature identical with Photoshop).
    The main reason I still have Photoshop in my professional life is not due to missing features in the alternatives I now use compared to Photoshop (as a matter of fact the combined power of the alternatives are superior in terms of provided features), but merely because the students I teach are taught the "industry standard", and I keep up knowledge-wise.
    Anyway, I am not expecting Photoshop to encompass the same functionality as Illustrator, nor do I want to compare Photoline's vector drawing tools to a dedicated vector illustration package. I am, however, experienced enough as a user (and a UX designer myself) to identify some very odd fragmented user interface behaviours in software.
    The new vector shapes are a very welcome recent addition in PH, though I question the strange disconnected implementation.

Maybe you are looking for

  • How to insert serial numbers in the creation of a delivery via VL01N

    Hello everybody, In the creation of an outbound delivery via VL01N I have to copy the serial number from a specific inbound delivery. I can get these serial numbers but I do not know where or how I can insert these serial numbers. I have to insert th

  • What are the requried fields to be mentioned for external application login

    Hi all, I want to integrate a authenticated external application with my portal. My problem is that in the source code of the page, which contains login and paasword box, the action url is given as ../servlet/searchdirectory?Path=http://mybeat.techma

  • How do I Kick Start a 940 on a Diamond?

    This setup works. MSI K9N2 Diamond AMD Athlon(tm) 64 X2 Dual Core Processor 6000+ Corsair 1000wtt PSU Patriot  PC2-6400 800mzh Nvidia 8800GTX x 2 WDC WD5000AACS-00G8B1 WDC WD3200AAJB-00TYA0 TSSTcorpCD/DVDW SH-S182D No hassle no problems I just plugge

  • Output for dvd player

    I don't use Premiere Pro very often so I would like to ask a question to avoid any problems. I work with Maya and I need to create a regular DVD in order to be played in a DVD player as opposed to a PC.   What settings do I need to be mindful of to a

  • SoundBlaster Audigy 2 ZS With Remote Controller RM-1500

    7SoundBlaster Audigy 2 ZS With Remote Controller RM-500N Hi, i got a computer here SCALEON X (fujitsu-siemens) and it has a SoundBlaster Audigy 2 ZS in it. So with it i got this RM-500 Remote Control, i cant get this to work. Iv been downloading alot