Java sorting the array of objects

Hi ,
I have a question on sorting objects in java.
I have a java interface some thing like :
public classmyObj extends Nullable
    private int objId;
    private Datemydate;
    public int getObjID();
    public Date getmyDate();
    public int getISecondD();
  }I need to create the array of the objects of this class that are sorted on the ObjID:
classmyObj[] collectionObjects
I need to pass this collectionObjects to another function.
Now how should I sort these objects based on the ObjID on collection?
Please help with this!
Thanks

neeto wrote:
Hi ,
I have a question on sorting objects in java.
I have a java interface some thing like :You mean class?
>
public classmyObj extends Nullable
private int objId;
private Datemydate;
public int getObjID();
public Date getmyDate();
public int getISecondD();
}I need to create the array of the objects of this class that are sorted on the ObjID:
classmyObj[] collectionObjects
I need to pass this collectionObjects to another function.
Now how should I sort these objects based on the ObjID on collection?Create a comparator and use it in a call to Collections.sort (or Arrays.sort if you have an array)

Similar Messages

  • How to sort an array of objects?

    I need to sort an array of objects. Each object has serial number, and other properties. I need to sort it by serial number.

    Do a java.util.Arrays.sort(). The method has quite a few overloads, so I'll give a complete example this time:import java.util.*
    public class SortDemo {
        public static void main(String args) {
            SimpleObject[] objs = new SimpleObject[10];
            for (int i=0; i<10; i++)
                objs=new SimpleObject();
    dump(objs);
    Comparator c = new SimpleComparator();
    Arrays.sort(objs, c);
    dump(objs);
    static void dump(Object[] o) {
    for (int i=0; i<o.length; i++)
    System.out.print(o[i] + " ");
    /** Object to demonstrate comparing with **/
    class SimpleObject {
    private int n = (int) (10*Math.random());
    public String toString() {
    return String.valueOf(getNumber());
    public int getNumber() {return n;}
    /** The custom comparator **/
    class SimpleComparator implements Comparator {
    public int compare(Object o1, Object o2) {
    return ((SimpleObject) o1).getNumber() - ((SimpleObject) o2).getNumber();
    public boolean equals(Object o) {return false;}
    }I could have made the SimpleObject class "Comparable", but a design like this allows more flexibility so I decided to use another class for the Comparator.

  • Sorting an array of objects

    hi there, i have to sort an array of object that looks like:
    surname, name, age, height
    well i have to sort them alphabetically like this:
    based on the surnames, if the surnames are the same than sort on the base of the names; if the names are the same sort them on the base of age and so on. If all the fields are the same the order is non important.
    Well I am not sure how I can do it using the Comparable Interface? as it is an interface i don't have any idea how to implement it

    This search took 2 seconds to do. And it's using your exact subject header. Next time try searching, instead of waiting forever hoping that someone will help you.
    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2B%22sorting+an+array+of+objects%22

  • Sorting an array of objects and returning another variable

    Hi there,
    Bit stuck on this one I wonder if anyone can help..
    I have an object array into which I've pushed a number of objects with different variables :-
    myArray.push({myRef: 1, myValue: "W"});
    I can sort the array in numerical order using :-
    myArray.sortOn("myRef", Array.NUMERIC);
    but after sorting I would like to collapse the array using something along the lines of :-
    myArray.join("");
    to join the OTHER variable (myValue)...
    Is it possible to do this without pushing every instance of 'myValue' to another array and then joining that ?
    Many Thanks in advance
    Martin

    Hi kglad,
    I really appreciate you helping, but I have had to completely change my approach to this problem, therefore I will be marking the question as answered !!
    Thanks again

  • Help sorting an array of objects needed please.

    I am trying to sort the array Students[] in descending order of Fees due. Using the code below I get a null pointer error at runtime. The array is not completely full, it has 20 cells, but the variable studentArrayCounter holds the number of used cells. The 'getFeesDue()' code returns an integer value.
    Any help is appreciated.
         // Sort Student Records Method
               public void sortStudentRecords()
                int loopCount = 0;
               for (loopCount = 1; loopCount < studentArrayCounter; loopCount ++)
              if(Students[loopCount].getFeesDue()>Students[loopCount-1].getFeesDue())
                   SortStudents[0]=Students[loopCount-1];
                   Students[loopCount-1]=Students[loopCount];
                   Students[loopCount]=SortStudents[0];
         }

    Also, unless the excersize is to write a sort algorigthm (which I kinda doubt) you should use Arrays.sort
    Arrays.sort(Students, new Comparator() {
      public int compare(Object o1, Object o2) {
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        return s1.getFeesDue() - s2.getFeesDue();
    });

  • Sorting an array of objects by an attribute

    I'm pretty new to java so don't laugh if you think my question is real easy!
    I have an array of objects and I want to sort them according to an integer value stored in each object. Any help would be very much appreciated.
    Thanks for looking!!

    Perhaps an example would help:
    public class Person {
      private String name;
      private int age;
      public void setName(String name) { this.name = name; }
      public void setAge(int age) { this.age = age; }
      public String getName() { return name; }
      public int getAge() { return age; }
    =====
    public class PersonAgeSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        Integer i1 = new Integer(p1.getAge());
        Integer i2 = new Integer(p2.getAge());
        return i1.compareTo(i2);
    =====
    public class PersonNameSorter implements Comparable {
      public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        String s1 = p1.getName();
        String s2 = p2.getName();
        return s1.compareTo(s2);
    =====
    import java.util.Arrays;
    public class SortExample {
      public static void main(String [] args) {
      Person p1 = new Person();
      Person p2 = new Person();
      p1.setName("Tom");
      p1.setAge(22);
      p2.setName("Nancy");
      p2.setAge(33);
      Person [] people = new Person[2];
      people[0] = p1;
      people[1] = p2;
      Arrays.sort(people, new PersonAgeSorter());
      Arrays.sort(people, new PersonNameSorter());
    }

  • Forwarding the array of object to servlet class

    Hi
    i am new to this j2ee.So please cooperate with me.
    i am having an array of objects in a jsp page.
    Each object represent a option which could be seelected through radio button.
    Now i want to send one selected object,corresponding to selected radio button to my servlet ManageUser.
    how can i do that.can any one help me please.
    i have been trying like this but i guess it is not correct .
    <%--   
    --%>   
    <%@page contentType="text/html" pageEncoding="UTF-8"%>    
    <%@page import="abc.javabean.EmpJavaBean"%>  
    <!--importing pages(classes) to implement request response  -->  
    <%@page import="javax.servlet.ServletException"%>  
    <%@page import="javax.servlet.http.HttpServlet"%>  
    <%@page import="javax.servlet.http.*"%>  
    <%@page import="javax.servlet.RequestDispatcher"%>  
    <%@page import="java.util.*"%>  
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
       "http://www.w3.org/TR/html4/loose.dtd">    
    <html>  
        <head>  
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
            <title>JSP Page</title>  
            <script type="text/javascript">  
                //function for selecting the radio  
                function validateRadio(fetchedArrayObject)  
                    alert("hi");  
                    var thisone=-1;  
                    for(i=0;i<document.searchedEmpForm.radioGroup.length;i++)  
                            if(searchedEmpForm.radioGroup.checked==true)
    thisone=i;
    alert(thisone);
    var name=fetchedArrayObject[i].getEmpName();
    alert(name);
    session.setAttribute("fetchedArrayObject[i]",fetchedArrayObject[i]);
    if(thisone==-1)
    alert("you must select a radio Button");
    return false;
    return true;
    </script>
    </head>
    <body bgcolor="#8db6cd">
    <!--retreaving the array values from the servlet -->
    <%
    //int a;
    EmpJavaBean fetchedArrayObject[]=new EmpJavaBean[4];
    fetchedArrayObject=(EmpJavaBean[])request.getAttribute("substituteArray");
    //a=fetchedArrayObject[0].getEmpNumber();
    %>
    <h3>ur new no is <%=fetchedArrayObject[0].getEmpNumber()%></h3><br>
    <form name="searchedEmpForm" action="/Precize/ManageUser" onsubmit="return validateRadio(fetchedArrayObject)">
    <br></br>
    <h2 align="center">Your Searched Result Is Here</h2>
    <br></br>
    <table border="1" align="center">
    <thead>
    <tr>
    <th> </th>
    <th> <input type="button" value="Emp#" name="searchedPageEmpNumb"> </th>
    <th> <input type="button" value="Name" name="searchedPageEmpName"> </th>
    <th> <input type="button" value="Priv" name="searchedPageEmpPriv"> </th>
    <th> <input type="button" value="Role" name="searchedPageEmpRole"> </th>
    <th> <input type="button" value="Start Date" name="searchedPageEmpStartDate"> </th>
    <th> <input type="button" value="End Date" name="searchedPageEmpEndDate"> </th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td><input type="radio" name="radioGroup" value="r11" ></td>
    <td><%=fetchedArrayObject[0].getEmpNumber()%></td>
    <td><%=fetchedArrayObject[0].getEmpName()%></td>
    <td><%=fetchedArrayObject[0].getEmpPrivilege() %></td>
    <td><%=fetchedArrayObject[0].getEmpRole()%></td>
    <td><%=fetchedArrayObject[0].getEmpStartdate()%></td>
    <td><%=fetchedArrayObject[0].getEmpEndDate() %></td>
    </tr>
    </tbody>
    </table>
    <br><center><input type="submit" value="Update" name="updateButton" ></center>
    <h3 align="center">Select the Employee To be Updated/deleted</h3>
    </form>
    </body>
    </html>
    please suggest me the answer.
    regards
    thanx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I think you need to learn the difference between "java" and "javascript"
    calling session.setAttribute from a javascript function will not have the effect that you desire.
    If you give all radio buttons the same "name", then request.getParameter("radioGroup") should tell you the value of the selected one.

  • Why can't the Web console in FF9.01 not see extensions I've added to the Array class (object)?

    I've added a number of new methods to the Array object in Javascript. My scripts see them fine, but the Web console reports them as 'undefined'. Apparently the console cannot see my changes. Why is that?

    Not the same. It should be like the orange indicator for an imported clip in the camera import window. It's really quite sophisticated in iMovie. When you switch projects the orange line changes to reflect what's in the open project so a clip might have the orange indicator when one project is open in the timeline, and not when another project is open. It's a really useful tool, because it even shows what parts of a clip have been used in the open project.

  • How to initialize the array with object?

    Here is type I have.
    CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_TYPE AS OBJECT
    BU_AP VARCHAR2(5),
    VOUCHER VARCHAR2(10),
    V_LINE INTEGER,
    USERID VARCHAR2(20),
    COMMENT_DTTM DATE,
    COMMENT VARCHAR2(254)
    CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_COLL AS VARRAY(1000) OF SYSADM.AP_COMMENT_TYPE;
    Then I created a procedure to grab some data.
    PROCEDURE get_voucher_comments (
    v_bu_in IN VARCHAR2,
    v_voucher_in IN VARCHAR2,
    v_line_in IN NUMBER,
    v_userid IN VARCHAR2,
    voucher_comment OUT      sysadm.ap_comment_coll
    IS
    i NUMBER := 1;
    v_comments VARCHAR2 (254) := ' ';
    comment_type sysadm.ap_comment_type;
    v_line_num NUMBER := 0;
    CURSOR get_all_comment
    IS
    SELECT voucher_line_num, descr254_mixed
    FROM ps_fas_ap_comment
    WHERE business_unit = voucher_comment (i).bu_ap
    AND voucher_id = voucher_comment (i).voucher;
    CURSOR get_line_comment
    IS
    SELECT descr254_mixed
    FROM ps_fas_ap_comment
    WHERE business_unit = voucher_comment (i).bu_ap
    AND voucher_id = voucher_comment (i).voucher
    AND voucher_line_num = voucher_comment (i).v_line;
    BEGIN
    voucher_comment (1) := ap_comment_type (' ', ' ', 0, ' ', '', ' ');
    --voucher_comment (1) := ap_comment_type (null, null, null, null, null,null);
    IF voucher_comment (i).v_line = 0
    THEN
    OPEN get_all_comment;
    LOOP
    FETCH get_all_comment
    INTO v_line_num, v_comments;
              voucher_comment.EXTEND;
    voucher_comment (i) :=
    ap_comment_type (v_bu_in,
    v_voucher_in,
    v_line_num,
    v_userid,
    TO_DATE (TO_CHAR (SYSDATE,
    'DD-MON-YYYY HH24:MI:SS'
    'DD-MON-YYYY HH24:MI:SS'
    v_comments
    i := i + 1;
    END LOOP;
    ELSE
    OPEN get_line_comment;
    LOOP
    FETCH get_line_comment
    INTO v_comments;
              voucher_comment.EXTEND;
    voucher_comment (i) :=
    ap_comment_type (v_bu_in,
    v_voucher_in,
    v_line_num,
    v_userid,
    TO_DATE (TO_CHAR (SYSDATE,
    'DD-MON-YYYY HH24:MI:SS'
    'DD-MON-YYYY HH24:MI:SS'
    v_comments
    i := i + 1;
    END LOOP;
    END IF;
    END get_voucher_comments;
    But when I tried to test the procedure, got error: ORA-06531: Reference to uninitialized collection. Does anyone have experience of handling array with object?
    declare
    O_voucher_comment SYSADM.AP_COMMENT_COLL;
    begin
    FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 1, 'KEHE', O_voucher_comment);
    end;

    Thanks for that. I changed it a little bit, but when i ran this script, got ORA-06532: Subscript outside of limit.
    declare
    O_voucher_comment SYSADM.AP_COMMENT_COLL := sysadm.ap_comment_coll(null);
    begin
    FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 0, 'KEHE', O_voucher_comment);
    end;
    PROCEDURE get_voucher_comments (
    v_bu_in IN VARCHAR2,
    v_voucher_in IN VARCHAR2,
    v_line_in IN NUMBER,
    v_userid IN VARCHAR2,
    voucher_comment OUT      sysadm.ap_comment_coll
    IS
    i NUMBER := 1;
    v_comments VARCHAR2 (254) := ' ';
    comment_type sysadm.ap_comment_type;
    v_line_num NUMBER := 0;
    CURSOR get_all_comment
    IS
    SELECT voucher_line_num, descr254_mixed FROM ps_fas_ap_comment
    WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in;
    CURSOR get_line_comment
    IS
    SELECT descr254_mixed FROM ps_fas_ap_comment
    WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in
    AND voucher_line_num = v_line_in;
    BEGIN
    --voucher_comment() := SYSADM.ap_comment_type (NULL, NULL, NULL, NULL, NULL, NULL);
    --' ', ' ', 0, ' ', '', ' ' sysadm.ap_comment_coll
    voucher_comment := sysadm.ap_comment_coll(null);
    IF v_line_in = 0
    THEN
    OPEN get_all_comment;
    LOOP
    FETCH get_all_comment
    INTO v_line_num, v_comments;
              if i > 1
              then
                   voucher_comment.EXTEND;
              end if;
    voucher_comment (i) := ap_comment_type (v_bu_in,
    v_voucher_in, v_line_num, v_userid,
    TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS'), v_comments );
    i := i + 1;
    END LOOP;
    ELSE
    OPEN get_line_comment;
    LOOP
    FETCH get_line_comment
    INTO v_comments;
              voucher_comment.extend(6);
    voucher_comment (i) := ap_comment_type (v_bu_in, v_voucher_in, v_line_num, v_userid, TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'DD-MON-YYYY HH24:MI:SS'), v_comments);
    i := i + 1;
    END LOOP;
    END IF;
    END get_voucher_comments;

  • Sorting an array of Objects based on a variable inside each object

    I have a class public class handInfo
              //VARS
                   int highC = 0;
                   int hVal = 0;
                   int numHand = 0;
              //CONSTRUCOTRS
                   public handInfo()
              //METHODS
                   public void setHC(int hc)
                             highC = hc;
                   public void setHV(int hv)
                             hVal = hv;
                   public void setNH(int nh)
                             numHand = nh;
                   public int getHC()
                             return highC;
                   public int getHV()
                             return hVal;
                   public int getNH()
                             return numHand;
         }now i have an array, handInfo[] hands = new handInfo[4];
                        hands[0] = new handInfo();
                        hands[0].setHC(HV);
                        hands[0].setNH(1);
                        hands[0].setHV(Val);
                        hands[1] = new handInfo();
                        hands[1].setHC(HV2);
                        hands[1].setNH(2);
                        hands[1].setHV(Val2);
                        hands[2] = new handInfo();
                        hands[2].setHC(HV3);
                        hands[2].setNH(3);
                        hands[2].setHV(Val3);
                        hands[3] = new handInfo();
                        hands[3].setHC(HV4);
                        hands[3].setNH(4);
                        hands[3].setHV(Val4);i need to know how to sort this array, based off hVal...
    D:

    Write a Comparator and call Arrays.sort(array, Comparator).

  • Displaying the contents of an array of objects

    Hello All,
    My Java teacher gave us a challenge and I'm stumped. The teacher wants us to display the contents of the array in the main menthod. The original code is as follows:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    }I understand that the elements of the array are objects, and each one has a value assigned to it. The following code was my first attempt at a solution:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
                                    for ( int i = 0; i < thingArray.length; i++)
                                       System.out.println( thingArray );                         
    }To which I'm given what amounts to garbage output. I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array. There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. Thanks very much in advance!

    robrom78 wrote:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    for ( int i = 0; i < thingArray.length; i++)
    System.out.println( thingArray );                         
    Note that you're trying to print the entire array at every loop iteration. That's probably not what you meant to do.
    You probably meant to do something more like
                                 System.out.println( thingArray[i] );Also, note that the java.util.Arrays class has a toString method that might be useful.
    To which I'm given what amounts to garbage output. It's not garbage. It's the default output to toString() for arrays, which is in fact the toString() defined for java.lang.Object (and inherited by arrays).
    I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array.It displays a default result that is vaguely related to the memory, but probably shouldn't be thought of us such. Think of it as identifying the type of object, and a value that differentiates it from other objects of the same type.
    By the way I assume you mean "+not+ the contents of the array" above. If so, that is correct.
    There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? No, you don't override a method in println; actually methods don't contain other methods directly. You probably do need to override toString in Thing.
    I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. You can get to the individual objects in the array just by dereferencing it, as I showed you above.
    But I suspect that won't be sufficient. Most likely, Thing doesn't have a toString method defined. This means that you'll end up with very similar output, but it will say "Thing" instead of "[Thing" and the numbers to the right of the "@" will be different.
    You'll need to override the toString() method in Thing to get the output you want.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trouble creating and populating an array of objects.

    I'm trying to create/populate an array of objects with consisting of a {string, double, integer}, and am having trouble getting this theory to work in Java. Any assistance provided would be greatly appreciated. Following are the two small progs:
    public class HairSalon
    { private String svcDesc; private double price; private int minutes;
    //Create a constructor to initialize data members
    HairSalon( )
    svcDesc = " "; price = 0.00; minutes = 0;
    //Create a constructor to receive data
         HairSalon(String s, double p, int m)
         svcDesc = s; price = p; minutes = m;
    //Create methods to get the data members
    public String getSvcDesc( )
         return svcDesc;
    public double getPrice( )
         return price;
    public int getMinutes( )
         return minutes;
    public class SortSalon
         public static void main(String[ ] args)
         SortSalon [] sal = new SortSalon[6];
    //Construct 6 SortSalon objects
              for (int i = 0; i < sal.length; i++)
              sal[i] = new SortSalon();
    //Add data to the 6 SortSalon objects
         sal[0] = new SortSalon("Cut"; 10.00, 10);
         sal[1] = new SortSalon("Shampoo", 5.00, 5);           sal[2] = new SortSalon("Sytle", 20.00, 20);
         sal[3] = new SortSalon("Manicure", 15.00, 15);
         sal[4] = new SortSalon("Works", 30.00, 30);
         sal[5] = new SortSalon("Blow Dry", 3.00, 3);
    //Display data for the 6 SortSalon Objects
         for (int i = 0; i < 6 ; i++ )
         { System.out.println(sal[i].getSvcDesc( ) + " " + sal.getPrice( ) + " " + sal[i].getMinutes( ));
         System.out.println("End of Report");

    Hey JavaMan5,
    That did do the trick! Thanks for the assistance. I was able to compile and run the program after adding my sorting routine. Do you happen to see anything I can do to clean it up further, or does it look ok? Thanks again,
    Ironjay69
    public class SortSalon
         public static void main(String[ ] args) throws Exception
         HairSalon [] sal = new HairSalon[6];      
         char selection;
    //Add data to the 6 HairSalon objects
         sal[0] = new HairSalon("Cut", 10.00, 10);
         sal[1] = new HairSalon("Shampoo", 5.00, 11);      
         sal[2] = new HairSalon("Sytle", 20.00, 20);
         sal[3] = new HairSalon("Manicure", 15.00, 25);
         sal[4] = new HairSalon("Works", 30.00, 30);
         sal[5] = new HairSalon("Blow Dry", 3.00, 3);
    System.out.println("How would you like to sort the list?");
         System.out.println("A by Price,");
         System.out.println("B by Time,");
         System.out.println("C by Description.");
         System.out.println("Please enter a code A, B or C, and then hit <enter>");
              selection = (char)System.in.read();
    //Bubble Sort the Array by user selection
              switch(selection)
              case 'A':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'a':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'B':
              BubbleSortTime(sal, sal.length);                    break;
                   case 'b':
              BubbleSortTime(sal, sal.length);
                   break;
                   case 'C':
              BubbleSortService(sal, sal.length);
                   break;
                   case 'c':
              BubbleSortService(sal, sal.length);
                   break;
                   default:
              System.out.println("Invalid Selection, Randomly Sorted List!");
    //Display data for the 6 HairSalon Objects
              for (int i = 0; i < sal.length ; i++ )
         System.out.println(sal.getSvcDesc( ) + " " + sal[i].getPrice( ) + " " + sal[i].getMinutes( ));
              System.out.println("___________");
              System.out.println("End of Report");
    public static void BubbleSortPrice(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by price
    int a, b;
    HairSalon temp;
    int highSubscript = len - 1;
    for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array.getPrice() > array[b + 1].getPrice())
              temp = array[b];
              array[b] = array [b + 1];
              array[b + 1] = temp;
    public static void BubbleSortTime(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
              for(b= 0; b < highSubscript; ++b)
         if(array[b].getMinutes() > array[b + 1].getMinutes())
         temp = array[b];
         array[b] = array [b + 1];
         array[b + 1] = temp;
    public static void BubbleSortService(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array[b].getSvcDesc().compareTo( array[b + 1].getSvcDesc()) > 0)
                   temp = array[b];
                   array[b] = array [b + 1];
                   array[b + 1] = temp;

  • 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

  • Problem with java applet and array of arrays

    hi!
    i'm passing an array of arrays from java applet using
    JSObject.getWindow(applet).call("jsFunction", array(array(), array()) );
    in every other browser than safari 4.0.2 it's no problem to iterate over this array. in safari "array.length" is undefined. is such construction supported in safari's js engine?
    Message was edited by: quaintpl
    Message was edited by: quaintpl
    Message was edited by: quaintpl
    Message was edited by: quaintpl
    Message was edited by: quaintpl

    Thanks for the answer but the problem is the type of object of method and how from pl/sql is posiblle to call.
    The method waiting a ArrayofAlicIva, but if i define this object is not posible to set the object inside the array because the wsdl not have this functions.
    I need to define array of objects but the object is inside is the diferent type of array.
    If i Define the array of object correct to object inside, the method expect that the other array type.
    Is a Deadlock ??
    The solution in Java is Simple
    AlicIva[] alicIva = new AlicIva[1];
    alicIva[0]= new AlicIva();
    alicIva[0].setId(Short.parseShort(1));
    fedr[0].setIva(alicIva);
    this is the method imported in java class to form
    -- Method: setIva (LArrayOfAlicIva;)V
    PROCEDURE setIva(
    obj ORA_JAVA.JOBJECT,
    a0 ORA_JAVA.JOBJECT) IS
    BEGIN
    args := JNI.CREATE_ARG_LIST(1);
    JNI.ADD_OBJECT_ARG(args, a0, 'ArrayOfAlicIva');
    JNI.CALL_VOID_METHOD(FALSE, obj, 'FECAEDetRequest', 'setIva', '(LArrayOfAlicIva;)V', args);
    END;

  • Problem with Java Clasess and Arrays

    Hello, i have a situation when a need to call a web services.
    I have 3 classes..and a need to call a method
    Class1 have a method
    public void setIva(ArrayOfAlicIva value)
    Class ArrayOfAlicIva is
    protected List<AlicIva> alicIva;
    This class not have a metho to set de object
    and
    Class AlicIva have 1 attributes call base int and method setBase
    When imported to Forms, i have the package with this clasess...
    The problem is when i have to call a SetIva Method.
    In pl/sql i have
    Case 1
    OraAlicIva := AlicIva.new(); --OK
    AlicIva.setBase(OraAlicIva , 10); --OK
    Class1.setIva(Object_to_Class1, OraAlicIva); --Error, is not type excpected
    Case 2
    OraAlicIva := ArrayOfAlicIva.new(); --OK
    AlicIva.setBase(OraAlicIva , 10); --Error, setBase is not defined
    Class1.setIva(Object_to_Class1, OraAlicIva); --OK
    Case 3
    OraAlicIva := AlicIva.new(); --OK
    OraAlicIva2 :=ORA_JAVA.NEW_OBJECT_ARRAY(1,'ArrayOfAlicIva'); --OK
    AlicIva.setBase(OraAlicIva , 10); --OK
    ORA_JAVA.SET_OBJECT_ARRAY_ELEMENT(OraAlicIva2 , 0, OraAlicIva); --Error, ExceptionStoreArray
    Class1.setIva(Object_to_Class1, OraAlicIva); --OK
    The Solutions in Java is
    AlicIva[] alicIva = new AlicIva[1];
    alicIva[0]= new AlicIva();
    alicIva[0].setId(Short.parseShort(1));                
    fedr[0].setIva(alicIva);}
    Is posible to Resolve ??
    Thanks and Sorry for my inglish

    Thanks for the answer but the problem is the type of object of method and how from pl/sql is posiblle to call.
    The method waiting a ArrayofAlicIva, but if i define this object is not posible to set the object inside the array because the wsdl not have this functions.
    I need to define array of objects but the object is inside is the diferent type of array.
    If i Define the array of object correct to object inside, the method expect that the other array type.
    Is a Deadlock ??
    The solution in Java is Simple
    AlicIva[] alicIva = new AlicIva[1];
    alicIva[0]= new AlicIva();
    alicIva[0].setId(Short.parseShort(1));
    fedr[0].setIva(alicIva);
    this is the method imported in java class to form
    -- Method: setIva (LArrayOfAlicIva;)V
    PROCEDURE setIva(
    obj ORA_JAVA.JOBJECT,
    a0 ORA_JAVA.JOBJECT) IS
    BEGIN
    args := JNI.CREATE_ARG_LIST(1);
    JNI.ADD_OBJECT_ARG(args, a0, 'ArrayOfAlicIva');
    JNI.CALL_VOID_METHOD(FALSE, obj, 'FECAEDetRequest', 'setIva', '(LArrayOfAlicIva;)V', args);
    END;

Maybe you are looking for