Sorting a Vector of custom-made classes.

Hi,
I have a class Car which has the following private members:
Strings year, make, model, engine and transmission.
I have another class CarList which extends Vector (a vector of Car objects).
I wish to create a method called "sortCarList()" in class CarList which will sort all of the Car objects in the vector first by "year", then by "make", then by "model". I am using a bubble sort. I tried simply sorting the Car objects in CarList by year using the "compareTo()" method. The comparison works fine, but the actual re-arranging of elements is causing me grief. Here's my current code for the "sortCarList()" method in vector class CarList:
public void sortCarList() {
for (int i = 0; i < (size() - 1); i++) {
for( int j = 0; i < (size() - 1); i++)     {
     if (elementAt(j).getYear().compareTo(elementAt(j + 1).getYear()) > 0) {
Car tempHolder;
     tempHolder = elementAt(j);
          elementAt(j) = elementAt(j + 1);
          elementAt(j + 1) = tempHolder;
I'm getting the error (NetBeans):
(Unexpected type)
required: variable
found : value
elementAt(j) = elementAt(j + 1);
--------------^
- and -
required: variable
found : value
elementAt(j + 1) = tempHolder;
--------------^
So I'm just getting the error because the way I'm trying to switch the vector elements with one another! I haven't coded in Java for a while and have since spent a college semester programming in COBOL so my reality is a bit fuddled. Is this a reference problem? Or is there something else I'm just not catching here? Help would be very appreciated!
After I get this first simple issue out of the way, I can then start implementing a more complex sort which also takes MAKE and MODEL into consideration.
So in the end I'm looking for this kind of sorting (fields separated for clarity):
YEAR-MAKE-MODEL
1969-Dodge-Super Bee
1969-Plymouth-Road Runner
1969-Pontiac-GTO
1970-Buick-GSX
1970-Chevrolet-Chevelle
As you can see, I want the first order of sorting to be YEAR, then MAKE, then MODEL, which I assume will be a pain to do (if element 0's MODEL value lexicographically higher in the alphabet than element 1's MODEL value, it shouldn't bother sorting them because the MAKES are already in proper order).
Message was edited by:
incogx
Message was edited by:
incogx
Message was edited by:
incogx

Here is an example of a Car class that implements the Comparable interface, and allows Cars to be sorted
by year, make, and model. Since what needs to be sorted are an Integer (year) and Strings (make and model)
which already implement the Comparable interface, this then allows a natural-order comparison to be made
on Cars. This comparison is implemented in the compareTo method at the bottom of the class.
There is a demo program that creates some Car data, sorts it, and prints it out. The sorting is the only
important statement; the rest of the code is for demonstration purposes only.
(The code is an adaption of an example in the Java Tutorial,
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
The tutorial has an explanation of some of the code, and is worth reading.)
HTH
import java.util.*;
public class Car implements Comparable<Car>
    private final Integer year;
    private final String make, model;
    public Car(Integer year, String make, String model)
        if (year == null || make == null || model == null)
            throw new NullPointerException();
        this.year = year;
        this.make = make;
        this.model = model;
    public int hashCode()
        return 255*year.hashCode() + 31*make.hashCode() + model.hashCode();
    public String toString()
        return year + " " + make + " " + model;
    public int compareTo(Car n)
        int lastCmp = year.compareTo(n.year);
        int nextCmp = make.compareTo(n.make);
        return (lastCmp != 0 ? lastCmp :
            nextCmp != 0 ? nextCmp :
                model.compareTo(n.model));
import java.util.*;
public class CarSort
    public static void main(String[] args)
        // This creates an array of 6 Car instances
        Car nameArray[] = {
            new Car(1969, "Dodge", "Super Bee"),
            new Car(1970, "Buick", "Roadmaster"),
            new Car(1969, "Pontiac", "GTO"),
            new Car(1970, "Chevrolet", "Chevelle"),
            new Car(1970, "Buick", "GSX"),
            new Car(1969, "Plymouth", "Road Runner")
        // And this loads the Cars into a List
        List<Car> names = Arrays.asList(nameArray);
        // The 2 prior statements just create some data for this demo program
        Collections.sort(names);
        System.out.println(names);
}

Similar Messages

  • Creating users using custom made class/UI in portal

    This is what i have to achieve,
    I need to create an interface in portal which will,
    1. Create users in the OID where the users extend a class which i have created in OID with my custom attributes.
    2. Then create them in portal and then assign them to default groups which will depend on a parameter in the user creation form.
    From reading various documents in Metalink and OTN i have understood that the wwsec_api package allows us to do all this except that it is all for a user which will extend a predefined set of classes.
    So i decided to do this
    1.Make entries into the OID using the DBMS_LDAP package using commands like
    emp_vals(1) := p_first_name;
    DBMS_LDAP.populate_mod_array(emp_array,DBMS_LDAP.MOD_ADD,'firstName',emp_vals);
    retval := DBMS_LDAP.add_s(emp_session,emp_dn,emp_array);
    2.Fire the wwsec_api.add_portal_user to create the portal user and then activate and assign him to the default group after running the provsyns.sql file
    The problem i face is that i get errors when i execute the said procedure from any other schema other than portal.
    When the procedure is recreated in the portal schema and executed it works fine.
    So i decided to create the entire package in the portal schema itself.
    Now the problem i face is that the proc would execute fine on the sql prompt but fail when called from the form created in portal based on this procedure.
    I found out that the execution fails when the wwsec_api.xxx calls are made.
    The exceptions are not specific and have the error code 1 => user defined exception
    To have a workaround for this i directly inserted into the wwsec_person$ table with no values for the GUID column( I know this is not recommended but i gave it a try)
    The insert worked fine but i still had to set his default group.I tried updating the rows for the user to set the default_group column but there seems to be a trigger on it which causes the update to fail.
    Also when i check up the wwsec_person$ table there two rows for each user that i created ,one without the GUID/default_group and the other with the GUID/default_group.I guess this is because of the trigger.
    If i try using the wwsec_api.set_defaultgroup api, the proc fails.
    It is quite interesting to note that all the steps mentioned above, grant access to the user to portal.
    But the place it fails is while setting the default group for the same which is of prime importance to me.
    Also because I am inserting directly into the tables i have also to delete them when the user is deleted, this is because i again cannot execute the delete_portal_user in the wwsec_api package from the browser.
    Surprisingly the wwsec_api.create_list function works fine.
    Once i have created the users all the manipulations like changing group memberships etc become easy as i just modify the required details in the OID itself.
    What i need is a proper/safe way to do what i have just mentioned above.
    Please help out ASAP as this is urgent.
    Regards,
    KK

    Based on your requirements, you should go about things a little differently...
    You have written your custom DBMS_LDAP code to create and populate the user entry including your custom objectclasses - good.
    You don't need to create the user profile in the Portal schema at all.
    To set the default group, just set the orcldefaultprofilegroup attribute in the user entry in OID. This should be set to the DN of the default group.
    When the user logs on, his profile will automatically be created, and the default group will also sync up with the user entry in OID (patch required - 2830252).
    Also, you should have DIP provisioning running so that updates to the orcldefaultprofilegroup attribute in OID are subsequently conveyed to the portal schema. It will also take care of automatically deleting the user profile from the portal if the user is removed from OID.
    Please see the Portal Configuration Guide on how to enable and activate the Directory Integration Platform (DIP) provisioning integration between OID and Portal

  • Change of Unicode attribute in a custom made class

    Hi,
    In relation to a Unicode conversion, I have a program that calls a Class ZHRxxx.
    After I have changed the attribute to Unicode check, I get a new error in the method Constructor:
    Class ZHRCLPA001,Method CONSTRUCTOR
    In the constructor method, you can only access instance attributes,instance methods, or "ME" after calling the constructor of the          
    superclass . . . . . .          
    The code is one line:
    method CONSTRUCTOR.
    Assign pernr to class attribute
    a_pernr = i_pernr.
    endmethod.
    Any ideas ?
    Thanks

    Hello Peter
    Alexander gave you already the answer. However, based on the naming of your z-class I assume that you are trying to read or access infotype tables. Are you aware of class <b>CL_PT_EMPLOYEE</b>? This class provides you with a simple acccess to any <b>infotypes</b> you need.
    [code&----
    *& Report  ZUS_SDN_CL_PT_EMPLOYEE
    REPORT  zus_sdn_cl_pt_employee.
    DATA:
      go_employee    TYPE REF TO cl_pt_employee.
    PARAMETERS:
      p_pernr        TYPE pernr_d,
      p_begda        TYPE begda,
      p_endda        TYPE endda.
    START-OF-SELECTION.
      go_employee ?= cl_pt_employee=>get_employee( p_pernr ).
      CALL METHOD go_employee->get_master_data
        EXPORTING
          im_begda = p_begda
          im_endda = p_endda
       IMPORTING
         EX_I0000 =  " infotype 0000
         EX_I0001 =  " infotype 0001
         EX_I0002 =  " infotype 0002
         EX_I0007 =
         EX_I0008 =
    Using this method you can access any infotype(s)
      CALL METHOD go_employee->if_pt_employee~get_infotypes
        EXPORTING
          i_itlist      =
         I_FROMDATE    =
         I_TODATE      =
         I_FILTER      =
         I_NOAUTHCHECK =
       IMPORTING
         E_RESULT      =
         E_RETCD       =
    END-OF-SELECTION.[/code]
    The class is final. However, if you need a class hierarchy simply define your z-classes having CL_PT_EMPLOYEE as instance attribute.
    Regards
      Uwe

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

  • Sorting with layout set for NewsBrowser and custom made properties

    Hi
    I have developed some custom made properties that is used for each document based on XML Form. But how can I obtain a custom sorting order based on my properties.
    After created a document I define some properties for company, department and process. And using the layout set for NewsBrowser I will have my documents sorted due to my processes. Lets say that I have set the properties for the process for some documents, e.g. SA1010, SA1010-1, SA1010-1a, how to obtain this sorting order in a KM-Navigation-iView using layout set for NewsBrowser?
    Regards
    Kay-Arne
    Message was edited by: Kay-Arne S.  Aarlie

    Hi Kay-Arne,
    A namespace defines a system area in which a property (defined by a property ID) is allowed to exist only once. So for your own predefined properties you should use an own namespace in order to be able to use a Property ID that is already available in another namespace. Check this link for more info:
    http://help.sap.com/saphelp_nw04/helpdata/en/1a/9a4a3b80f2ec40aa7456bc87a94259/frameset.htm
    In the Property Definition you later use the Namespace Alias. This alias (with ":PropertyID") you would also use in the LayoutSet Parameter mentioned above.
    Hope this clarify things ,
    Robert

  • Sorting a vector of objects?

    I'm having a real hard time sorting my vector, which contains objects that are made up of 4 Strings and 1 integer each.
    This is what I have for the sort routine, but something needs to go in the line that has "if (current.compareTo(smallest) < 0 )" to make it access the name fields of the current and smallest elements.
    Any ideas?
    Thanks,
    Mike
    private void sortname() {
         int nextslot;
         int max = cust_rex.size()-1;
         for (nextslot = 0; nextslot < max; nextslot++) {
              int j = getSmallestName(nextslot);
              swap (nextslot, j);
    private void swap(int a, int b) {
         Object temp = cust_rex.elementAt(a);
         cust_rex.setElementAt(cust_rex.elementAt(b),a);
         cust_rex.setElementAt(temp,b);
    private int getSmallestName (int k) {
         if (cust_rex == null || cust_rex.size() <= k)
              return -1; //error value
         int small = k;
         for (int i = k + 1; i < cust_rex.size(); i++) {
         Customer current = (Customer) cust_rex.elementAt(i);
         Customer smallest = (Customer) cust_rex.elementAt(small);
         if (current.compareTo(smallest) < 0 )
              small = i;
         return small;
         }

    Look at java.util.Comparator and write your own comparator. Then look at java.util.Collections and use the sort method from there instead of writing your own.

  • Custom-made components & midp4palm

    Hi all,
    I've developed two simple custom-made components by subclassing canvas. One is a simple button, which you can push with the palm pointer.
    The other is a sort of textfield. The problem arises when I try to input text into this component... the Palm does not have a keyboard! And the little keyboard which pops when you press the dot under the "abc" image does not pop!
    Is there some way to make that keyboard appear?
    Any help would be greatly apreciated.
    Thanks,
    Estanis.

    the current api does not allow text to be placed into the canvas class. i would recommend u to use a textbox class. so if the user clicks on the canvas screen, it will call up the textbox class and allows the user to key in some data.then upon returning back to the canvas class, u can just update the display using repaint method.
    hope this helps.
    regards,
    joseph

  • Sorting a Vector of Doubles

    Is there an API function to sort a vector of Doubles from least to greatest or vica versa, or would i need to do that manually?

    java.util.Collection class has method sort(List list) and method sort(List list, Comarator c) you could use either one of thes, since java.util.Vector implements interface List.
    probably if you use the version of sort without comparator, then it sorts in the ascending order, but if you want to sort in descending order, then you'd need to create your own custom comparator that causes list to be sorted the other way... (see documentations and APIs for other details -- docs and apis may be found through link in the left column of this page)

  • How to sort a Vector that stores a particular object type, by an attribute?

    Hi guys,
    i need help on this problem that i'm having. i have a vector that stores a particular object type, and i would like to sort the elements in that vector alphabetically, by comparing the attribute contained in that element. here's the code:
    Class that creates the object
    public class Patient {
    private String patientName, nameOfParent, phoneNumber;
    private GregorianCalendar dateOfBirth;
    private char sex;
    private MedicalHistory medHistory;
    public Patient (String patientName, String nameOfParent, String phoneNumber, GregorianCalendar dateOfBirth, char sex) {
    this.patientName = patientName;
    this.nameOfParent = nameOfParent;
    this.phoneNumber = phoneNumber;
    this.dateOfBirth = dateOfBirth;
    this.sex = sex;
    this.medHistory = new MedicalHistory();
    Class that creates the Vector.
    public class PatientDatabase {
    private Vector <Patient> patientDB = new Vector <Patient> ();
    private DateFunction date = new DateFunction();
    public PatientDatabase () throws IOException{
    String textLine;
    BufferedReader console = new BufferedReader(new FileReader("patient.txt"));
    while ((textLine = console.readLine()) != null) {
    StringTokenizer inReader = new StringTokenizer(textLine,"\t");
    if(inReader.countTokens() != 7)
    throw new IOException("Invalid Input Format");
    else {
    String patientName = inReader.nextToken();
    String nameOfParent = inReader.nextToken();
    String phoneNum = inReader.nextToken();
    int birthYear = Integer.parseInt(inReader.nextToken());
    int birthMonth = Integer.parseInt(inReader.nextToken());
    int birthDay = Integer.parseInt(inReader.nextToken());
    char sex = inReader.nextToken().charAt(0);
    GregorianCalendar dateOfBirth = new GregorianCalendar(birthYear, birthMonth, birthDay);
    Patient newPatient = new Patient(patientName, nameOfParent, phoneNum, dateOfBirth, sex);
    patientDB.addElement(newPatient);
    console.close();
    *note that the constructor actually reads a file and tokenizes each element to an attribute, and each attribute is passed through the constructor of the Patient class to instantiate the object.  it then stores the object into the vector as an element.
    based on this, i would like to sort the vector according to the object's patientName attribute, alphabetically. can anyone out there help me on this?
    i have read most of the threads posted on this forum regarding similar issues, but i don't really understand on how the concept works and how would the Comparable be used to compare the patientName attributes.
    Thanks for your help, guys!

    Are you sure that you will always sort for the patient's name throughout the application? If not, you should consider using Comparators rather than implement Comparable. For the latter, one usually should ensure that the compare() method is consistent with equals(). As for health applications it is likely that there are patients having the same name, reducing compare to the patient's name is hazardous.
    Both, Comparator and Comparable are explained in Sun's Tutorial.

  • Custom object class attributes are not provisioning in oID thru OIM

    Hi,
    I have connected OIM with oID user provisioning is also taking place. I have made one custom structure class with some attributes in OID.
    In form designer,in OID usr form i have made feild UD_OID_USR_Custom
    In OId .config lookup i have mentioned that custom class as well as attributes of class[in code Custom in decode name of attribute at target]
    In process form recon mapping of OID i mapped this feild name .
    Also in resource object recon mapping also i mentioned this attribute.
    But while creating user till process form value of attribute is populating and not provisiong that attribute in OID.
    Please tell me where i went wrong or exact steps of mapping in form designer,Process definition,Lookup.OID.configuration,Resource objects.
    Thanks

    process form recon mapping of OID i mapped this feild nameHave you made attribute entry in Provisioning Lookup AttrName.Prov.Map.OID ?
    Have you followed each step :
    http://download.oracle.com/docs/cd/E11223_01/doc.904/e10436/extnd_func.htm#CACICHDH

  • Sort a vector of objects by one of its attributes

    Hi all!
    I have created this class:
    public class Client {
    private int numero;
    private double tempsEntrada;
    private double tempsServei;
    private double tempsIniciSessio;
    private char tipus;
    * Creates a new instance of Client
    public Client(int num, double temp,double servei, char tip) {
    numero = num;
    arrivalTime = temp;
    serviceTime = servei;
    tipus = tip;
    public char getTipus()
    return tipus;
    public int getNumero()
    return numero;
    public double getTempsEntrada()
    return arrivalTime;
    public double getTempsServei()
    return serviceTime;
    Now I've done a java vector of this object, and I want to sort it by arrivalTime.
    The class comparer looks like this
    public class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    double temps1 = ((Client)obj1).getTempsEntrada();
    double temps2 = ((Client)obj2).getTempsEntrada();
    return (int)(temps1 - temps2);
    now when I do Collections.sort(vector);
    this is the error reported:
    Exception in thread "main" java.lang.ClassCastException: cafevirtual.Client cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.sort(Arrays.java:1079)
    at java.util.Collections.sort(Collections.java:117)
    at cafevirtual.Main.main(Main.java:76)
    Java Result: 1
    what's wrong?
    thanks!

    Your Client class does not implement Comparable. You have to specify the Comparator to use: Collections.sort(vector, new Comparer());

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • Sorting a vector using the selection sort method

    I have to write a program that sorts a Vector using the selection sort algorithm. Unfortunately the textbook only has about 2 pages on vectors so needless to say I'm pretty clueless on how to manipulate vectors. However I think I'm on the right path, however I'm stuck on one part as shown in the code below.     
    private static void  selectionSort(Vector parts)
          int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
              smallestIndex = index;
              for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
               if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))  // this is where I'm having trouble
                  smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp); if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
    is returning "ProcessParts3.java:51: operator < cannot be applied to java.lang.Object,java.lang.Object"
    Here is the full program:
    import java.util.*;
    import java.io.*;
    public class ProcessParts3
         static Vector parts;
         public static void main(String[] args)
              loadVector();
         private static void loadVector()
         try
              Scanner fileIn = new Scanner(new File("productionParts.txt"));
              parts = new Vector();
              String partIn;
              while (fileIn.hasNext())
                   partIn = fileIn.nextLine();
                        parts.addElement(partIn.trim());
              selectionSort(parts);
                   for (int i = 0; i < parts.size(); i ++)
                   System.out.println(parts.elementAt(i));
         catch(Exception e)
              e.printStackTrace();
         private static void  selectionSort(Vector parts) //from this part down I'm responsible for the coding, everything
                                                               // everything above this was written by the teacher
                 int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
                smallestIndex = index;
                for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
                    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
                        smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp);
    }Edited by: SammyP on Nov 27, 2009 11:43 AM

    SammyP wrote:
    I have to write a program that sorts a Vector using the selection sort algorithm...Hmmm.... Your teacher is, in my humble opinion, a bit of a tard.
    1. Vector is basically deprecated in favor of newer implementations of the List interface which where introduced in [the collections framework|http://java.sun.com/docs/books/tutorial/collections/index.html] with Java 1.5 (which became generally available back in May 2004, and went end-of-support Oct 2009). ArrayList is very nearly a "drop in" replacement for Vector, and it is much better designed, and is marginally more efficient, mainly because it is not syncronised, which imposes a small but fundamentally pointless overhead when the collection is not being accessed across multiple threads (as is the case in your program).
    2. Use generics. That "raw" Vector (a list of Objects) should be a genericised List<String> (a list of Strings)... because it's compile-time-type-safe... mind you that definately complicates the definition of your static sort method, but there's an example in the link... Tip: temp should be of type T (not int).
    Note that String implements [Comparable<String>|http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html], so two String's can safely be compared using the compareTo method... In Java the mathematical operators (<, >, &#43;, -, /, &#42;, etc) are only applicable to the primitive types (byte char, int, float, etc)... The Java Gods just chose to muddy the waters (especially for noobs) by "overloading" the &#43; operator for String (and String only) to enable succinct, convenient string-concatenation... which I personally now see as "a little bit of a mistake" on there part.
         private static void  selectionSort(Vector parts)  {
    int index, smallestIndex, minIndex, temp = 0;
    for (index = 0; index < parts.size() - 1; index++) {
    smallestIndex = index;
    for (minIndex = index + 1; minIndex < parts.size(); minIndex++) {
    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex)) {
    smallestIndex = minIndex;
    parts.setElementAt(temp, smallestIndex);
    parts.setElementAt(smallestIndex, index);
    parts.setElementAt(index, temp);
    }3. ALLWAYS use {curly braces}, even when not strictly necessary for correctness, because (a) they help make your code more readable to humans, and also (b) if you leave them out, you will eventually stuff it up when you insert a line in the expectation that it will be part of the if statement (for example) but you forgot to also add the now mandatory curly-braces... This is far-too-common source of bugs in noob-code. Almost all professionals, nearly allways allways use curly braces, most of the time ;-)
    4. Variable names should be meaningful, except (IMHO) for loop counters... Ergo: I'd rename index plain old i, and minIndex to plain old j
        for ( int i=0; i<list.size()-1; ++i) {
          int wee = i; // wee is the index of the smallest-known-item in list.
          for ( int j=i+1; j<list.size(); ++j ) {Cheers. Keith.
    Edited by: corlettk on 28/11/2009 09:49 ~~ This here fraggin forum markup friggin sucks!

  • Sorting a vector

    hi
    all i am having problem with sorting a vector.I have a vector which contain Objects and each object has string values
    Vector->Objects->String 1 string 2 string 3;
    now i want to sort by string 2 but i also want to sort it by string 3 i means vector should be able to sort by string 2 and second preriority to string 3 and then string1.
    How can i do this i am over loading the comparator class.
    Collection.sort(vector, new vecComparetor());
    public int compare(Object obj1, Object obj2) {
    retrun obj1.compareTo(obj2);
    }

    If I guessed correctly your class is something like the following:
    package mydomain;
    public class MyClass{
         private String str1, str2, str3;
         public MyClass( String str1, String str2, String str3){
              this.str1 = str1;
              this.str2 = str2;
              this.str3 = str3;
         public String getStr1(){ return str1;}
         public String getStr2(){ return str2;}
         public String getStr3(){ return str3;}
         public String toString(){ return "(" + str1 + ", " + str2 + ", " + str3 + ")";}
    }Now, your problem is: Order Vector of MyClass objects by str2, then by str1, then by str3.
    So here it is your Comparator:
    package utils;
    import mydomain.MyClass;
    import java.util.Comparator;
    public class MyComparator implements Comparator{
         public int compare( Object o1, Object o2){
              int i = 0;
              return (i = ((MyClass)o1).getStr2().compareTo( ((MyClass)o2).getStr2())) != 0? i:
                    ((i = ((MyClass)o1).getStr1().compareTo( ((MyClass)o2).getStr1())) != 0? i:
                    ((i = ((MyClass)o1).getStr3().compareTo( ((MyClass)o2).getStr3())) != 0? i: 0));
    }Try it out with this tester (cut and paste these three classes. They compile and run.):
    package utils;
    import mydomain.MyClass;
    import java.util.Vector;
    import java.util.Collections;
    public class MyComparatorTest{
         public static void main( String[] args){
              Vector v = new Vector();
              for( char x = 'a'; x <= 'c'; x++){
                   for( char y = 'a'; y <= 'c'; y++){
                        for( char z = 'a'; z <= 'c'; z++){
                             v.add( new MyClass( new Character( x).toString(), new Character( y).toString(), new Character( z).toString()));
              System.out.println( v);
              Collections.sort( v, new MyComparator());
              System.out.println( v);
    }

  • HCM - Custom extractor class in smartform HRRCF_PUBLICATIONS_INT

    How to build custom extractor class ? I have a requirement where you have to change the standard layout of HRRCF_PUBLICATIONS_INT to include the custom fields and the data should be pulled from the custom extractor class. Any pointers regarding this is highly appreciated.

    Hi Nisha,
    I think you have an issue to call custom BSP.
    -     Ignore the warning message (in the table T77RCF_LOG_APPL) as it is just a warning message. I did not touch start page link at all.
    -     Additionally you need to make (I had to made) an entry in table u2018V77RCF_SMG_NAVIu2019.
    Let me know, if you need anything else.
    ...Naddy

Maybe you are looking for