Array sort with objects?

hits = searcher.search(query);
//java.util.Vector sortHits = new java.util.Vector ();
int[][] sortHits = new int[hits.length()][1];
// assign values to array
int teller = 0;
for (int i = 0; i < hits.length(); i++)
     Document doc = hits.doc(i);
     String absnumtxt = doc.get("absnumtxt");
     if(sAllCookies.indexOf(absnumtxt) >= 0){
          sortHits[0] = Integer.parseInt(absnumtxt);
          teller++;
          continue;
But the method Arrays.sort(sortHits); causes a ClassCastException error. Somebody an idea to solve this?
The structure is:
sortHits[0][0] = 2
sortHits[1][0] = 0
sortHits[2][0] = 0
sortHits[3][0] = 0
sortHits[4][0] = 0
sortHits[5][0] = 0

A two-dimentional array is an array of array of something.
Sorting a two-dimentional array requires a Comparator, because you compare uni-dimentional arrays, and arrays are not naturally comparable.
(BTW, why declaring a two-dimentional array here? you set the second dimention length to 1... a simple array would make it, no?)

Similar Messages

  • Structure of arrays sort

    Hi, I have a structure of arrays as follows.
    The Structure is session.cart
    my arrays are session.cart.foodname[ ]
    session.cart.comments[ ]
    session.cart.name[ ]
    session.cart.price[ ]
    All of these arrays correspond to each other, so
    session.cart.name[1] may be John, who ordered a cheeseburger
    (session.cart.foodname[1]). So i need to sort these by the persons
    name and have the other 3 arrays sort with them, so they still
    correspond to each other. Can anyone help me with this? Ive looked
    over the structsort function but cant figure out how to apply it to
    a structure of arrays. Thanks for the help.

    I would avoid using multiple arrays, which have to refer to
    each other - without really having a proper way to execute the
    plan. Structures are better for this. I created an example, which
    you might try out, and see if it fits your needs:
    <cfscript>
    session.cart.item = structnew();
    // use the name also as a key
    session.cart.item["john"]=structnew();
    session.cart.item["john"]["name"] = "john";
    session.cart.item["john"]["foodname"] = "Ribs";
    session.cart.item["john"]["price"] = "13.99";
    session.cart.item["john"]["comments"]="Johncomment";
    session.cart.item["mary"]=structnew();
    session.cart.item["mary"]["name"] = "mary";
    session.cart.item["mary"]["foodname"] = "Apple";
    session.cart.item["mary"]["price"] = "0.49";
    session.cart.item["mary"]["comments"]="Marycomment";
    session.cart.item["adam"]=structnew();
    session.cart.item["adam"]["name"] = "adam";
    session.cart.item["adam"]["foodname"] = "Cake";
    session.cart.item["adam"]["price"] = "4.99";
    session.cart.item["adam"]["comments"]="Adamcomment";
    // the following line actually does all you ever wanted.
    arrayToList() is just a bonus
    // for easy-to-understand-output in the end. More elegant
    solutions may exist. :-)
    nameList =
    arrayToList(structSort(session.cart.item,"textnocase","asc","name"));
    </cfscript>
    <cfoutput>
    <cfloop list="#nameList#" index="currentName">
    #session.cart.item[currentName].name#<BR>
    #session.cart.item[currentName].foodname#<BR>
    #session.cart.item[currentName].price#<BR>
    #session.cart.item[currentName].comments#<BR>
    <HR>
    </cfloop>
    </cfoutput>

  • Array.sort(Object[], comparator) problems

    I have been trying for days to figure out how to sort my array of geneInfo ono the field score1.
    when i try to use Arrays.sort(gInfo, new score1Comp()) it turns all of the array null.
    class score1Comp implements Comparator
    public int compare(Object o1, Object o2)
    geneInfo g1 = (geneInfo)o1;
    geneInfo g2 = (geneInfo)o2;
    // added these checkers to get rid of nullPointerException, but checked to see that most are non null
    if(g1==null&&g2==null)
    return 0;
    if(g1==null)
    return -1;
    if(g2==null)
    return 1;
    if(g1.getScore1() == g2.getScore1())
    return 0;
    else
    double temp = g1.getScore1() - g2.getScore1();
    System.out.println("score g1 - score g2: " + temp);
    System.out.println("rounded: " + (int)Math.round(temp));
    return (int)Math.round(temp);
    public boolean equals(Object obj)
    return obj.equals (this);
    }

    You have sorting your array with null to be the least on value object. For example here:
    MyObject[] objs = new MyObject[1000];
    objs[0] = new MyObject(3);
    objs[1] = new MyObject(2);
    objs[2] = new MyObject(1);
    Arrays.sort(objs, new score1Comp());Guess what the result would be? Your array would have the first 997 elements become null and the last 3 would be sorted to (1), (2), (3).
    So the cause is how your Comparator treats the null value. The solution could be to make sure your sorting array is filled correctly, or reverse the return 1/-1 for the null treatment.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

  • Need to sort an object array using an element in the object.

    hi all,
    i need to sort an object array using an element in the object.can someone throw some light on this.
    Edited by: rageeth on Jun 14, 2008 2:32 AM

    [http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html]

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

  • Filling a jtable with an array of Portfolio objects

    I have created a class Portfolio and want to put an array of portfolio objects in a Jtable.
    I created a tablePortfolioClass based on the AbstratTableModel and
    changed the classical 2 dimensional data array into a one dimensional arry of portfolio objects.
    The databaselayer correctly fills the Portfolio but does not display it inthe table...
    what am I doing wrong ?
    package DBpackage;
    import java.lang.String;
    public class Portfolio
    public Portfolio()
    public Portfolio(String sE)
    sEcode=sE;
    //here are normally set and getmethods that I left out
    private String sEcode;
    private double dQuantity;
    private double dAvgPrice;
    private double dPrice;
    private double dExchRate;
    private double dReturn;
    private String sDescr;
    private double dPerc;
    private double dTotal;
    =============================================================
    package DBpackage;
    import javax.swing.table.AbstractTableModel;
    class tablePortfolioClass extends AbstractTableModel
    Portfolio[]data=new Portfolio[50];
    final String[] columnNames={"Ecode","Description","Quantity","Price", "Avg","%","Total","Return"};
    public void tablePortfolioClass (int nrofRows)
    iRows=nrofRows;
    public void tablePortfolioClass(Portfolio[] pp)
    data=pp;
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row];
    public void setValueAt(Portfolio value, int row, int col) {
    data[row] = value;
    fireTableCellUpdated(row, col);
    private int iRows;
    private int iCols=4;
    =============================================================
    this is what is done in the frame
    Portfolio [] pf=new Portfolio[50];
    tablePortfolioClass pp=new tablePortfolioClass();
    //tablePortfolioClass pp=new tablePortfolioClass(pf); this one does not compile
    JTable grdPP=new JTable(pp);
    grdPP.setPreferredScrollableViewportSize(new Dimension(200,200));
    JScrollPane jscrollPanePP=new JScrollPane(grdPP);
    all more traditional implementations of the jtable work without any problem...
    anyone ?

    Your getValueAt() method should return the actual value you want to display in the table at the given row and column. Right now, it returns the whole Portfolio object. How is the table supposed to render a Portfolio object?
    Something more like this would make more sensepublic Object getValueAt(int row, int col)
      switch (col) {
      case 0:
        return data[row].getEcode();
      case 1:
        return data[row].getDescr();
      case 7:
        return new Double(data[row].getReturn());
    }The same can be said for your setValueAt() method. It should set the individual attributes of the Portfolio object at the given row rather than changing the whole object.

  • Need Help for Array with Object

    hey there guys... am trying to complete my project which is to create a Library System. Was able to create a list to show the books available when they select the book and click a borrow button it can print out the book.
    what problem i have now is that when a student click borrow... the value how can i transfer to an array inside the object student.
    i am usin a main screen (ms) who is controlling all the functions. been trying and trying on this for very long hopefully there will be those who are able to help me out.
    my customer screen would be like this... but how can i add in the array for books borrowed
    import javax.swing.*;
    class Customer
         private String name;
         private int accNo;
         private String password;
         private double balance;
         private Books borrow[]=new Books[5];
         int borrowCount=0;
         static int customerCount=0;
         private MainScreen ms;
         Customer(String n, int no, String p, double b)
              name=n;
              accNo=no;
              password=p;
              balance=b;
              customerCount++;
              JOptionPane.showMessageDialog(null,name +" record created");
              display();
    /* Trying to Create the Array to store information
         public void setStudentBorrow(String a)
              borrow[borrowCount]=a;
              borrowCount++;
              JOptionPane.showMessageDialog(null,"Book Borrowed");
         public String getStudentBorrow()
              for(int i=0;i<borrowCount-1;i++)
              {     return borrow;     }
         public String getPassword()
         {     return password;     }
         public String getName()
         {     return name;          }
         public int getAccNo()
         {     return accNo;     }
         public double getBalance()
         {     return balance;     }
         public void setName(String n)
         {     name=n;     }
         public void setPassword(String p)
         {     password=p;     }
         public void setBalance(double b)
         {     balance=b;     }
         public void setAccNo(int no)
         {     accNo=no;     }
         public void display()
              JOptionPane.showMessageDialog(null,
              "\nCutomer Number : "+ customerCount+
              "\nName :"+name+
              "\nAccount Number: "+accNo+
              "\nBalance (RM): "+balance,"Customer record",
              JOptionPane.INFORMATION_MESSAGE     );

    Cross Post:
    http://forum.java.sun.com/thread.jspa?threadID=779224&messageID=4433689#4433689

  • Modifying Array position with IViewCursor

    I have array print with command
    Alert.show(''+ObjectUtil.toString(arrColl));
    (mx.collections::ArrayCollection)#0
    filterFunction = (null)
    length = 4
    list = (mx.collections::ArrayList)#1
    length = 4
    source = (Array)#2
    [0] (Object)#3
    2008-03 = "1473"
    2008-03p = "40,19"
    desc = "Usuários únicos"
    [1] (Object)#4
    2008-03 = "1476"
    2008-03p = "-16,80"
    desc = "Novos usuários"
    [2] (Object)#5
    2008-03 = "53114"
    2008-03p = "39,25"
    desc = "Sessões"
    [3] (Object)#6
    2008-03 = "45"
    2008-03p = "-97,78"
    desc = "Tarifação"
    uid = "8B1A7D6D-62D1-C9BF-85DD-C538F40ED10D"
    sort = (null)
    source = (Array)#2
    I would like to modify the position of the Array, moving the
    last key for the beginning.
    thus:
    [0] (Object)#3
    desc = "Usuários únicos"
    2008-03 = "1473"
    2008-03p = "40,19"
    [1] (Object)#4
    desc = "Novos usuários"
    2008-03 = "1476"
    2008-03p = "-16,80"
    [2] (Object)#5
    desc = "Sessões"
    2008-03 = "53114"
    2008-03p = "39,25"
    [3] (Object)#6
    desc = "Tarifação"
    2008-03 = "45"
    2008-03p = "-97,78"
    my code source, but is not functioning. some tip of the
    error?
    /code]
    //Recebi o resultado e guarda em um array devido
    ordenação
    var arrColl:ArrayCollection = new ArrayCollection(event.data
    as Array);
    Alert.show(''+ObjectUtil.toString(arrColl));
    if (! runBefore) {
    runBefore=true;
    for (var i:int=0; i < arrColl.length; i++)
    // Get an IViewCursor object for accessing the collection
    data.
    var myCursor:IViewCursor=arrColl
    .createCursor();
    // Get the original collection length.
    var oldLength:int=arrColl.length;
    myCursor.seek(CursorBookmark.LAST);
    // The cursor is initially at the first item; delete it.
    var removedItem:Object=Object(myCursor.remove());
    // The cursor is at the (new) first item;
    // move it to the firs item.
    myCursor.seek(CursorBookmark.FIRST, 0);
    // Add removedItem as the first item.
    myCursor.insert(removedItem);
    var sort:Sort = new Sort();
    arrColl.sort=sort;
    // Refresh the collection view to apply the sort.
    arrColl.refresh();
    //Guarda na variavel o array
    dgReport.dataProvider = arrColl;
    [/code]

    No tip??

  • Sort an object by different fields

    Hello!
    Sorry for the (maybe) bad englisch but I'm a German.
    If I have an object fith different fields for example field1, field2, field3.
    To write a method which sorts an array of this objects by a given field?
    I mean something like this
    sort(String field, object[] o) {
    //sort by field
    instead of this
    sortbyfield1(object o){
    //sort by "field1"
    sortbyfield2(object[] o){
    //sort by "field2"
    hope you understood
    thanks
    Stefan

    When faced with this problem I usually use a Comparator helper class. Depending on whether the Comparator can be re-used I'll create a separate class or if not an inner or anonymous inner class. For example:
    import java.util.Comparator;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Collections;
    public class Main {
      // Compares Fields.f1 ascending
      public Comparator c1 = new Comparator() {
        public int compare(Object o1,
                           Object o2) {
          return ((Main.Fields)o1).f1.compareTo(((Main.Fields)o2).f1);
      public void sortem() {
        // Create our array of objects
        Object[] array = new Object[] {
          new Fields(new Integer(1),3,"3"),
          new Fields(new Integer(2),2,"1"),
          new Fields(new Integer(3),1,"2")
        // Sort on Field.f1 using reusable comparator
        Arrays.sort(array,c1);
        System.out.println(Arrays.asList(array));
        // Sort on Field.f2 using inner class
        Arrays.sort(array,new C2());
        System.out.println(Arrays.asList(array));
        // Sort on f3 using an anonymous inner class
        Arrays.sort(array, new Comparator(){
          public int compare(Object o1,
                           Object o2) {
            return((Main.Fields)o1).f3.compareTo(((Main.Fields)o2).f3);
        System.out.println(Arrays.asList(array));
      public static void main(String[] args) {
        Main m = new Main();
        m.sortem();
      // Class with many fields of different types
      class Fields {
        public Integer f1;
        public int     f2;
        public String  f3;
        public Fields(Integer f1, int f2, String f3) {
          this.f1 = f1;
          this.f2 = f2;
          this.f3 = f3;
        public String toString() {
          return ""+f1+" "+f2+" "+f3;
      // Inner class comparator on Field.f2
      class C2 implements Comparator {
        public int compare(Object o1,
                           Object o2) {
          int result = 0;
          int i1 = ((Main.Fields)o1).f2;
          int i2 = ((Main.Fields)o2).f2;
          if (i1==i1) result = 0;
          if(i1<i2) result = -1;
          else if (i1>i2) result = 1;
          return result;

  • Fastest Array sort method =Flashsort?

    i'm using Array.sort(object) method to sort the array but the running time is getting slower and slower as the size and number of arrays increase.
    As far as i know, Java uses quicksort for Array.sort() and the running time is O(nlogn) with n is the size of the array. Even it's one of the fastest algorithm out there, it will take too long to sort a big number of array.
    I heard that flashsort is the fastest algorithm with running time of O(n). This algorithm is by Dr. Karl-Dietrich Neubert's.
    Anyone wrote one class already that i can use like Flashsort.sort(array a) ?

    There are various implementations of this algorithm on
    this page:
    http://www.neubert.net/Flacodes/FLACodes.html
    I haven't studied it but I had the impression that you
    need to assume some things about the input data to get
    O(n) time complexity; this isn't the only O(n) sorting
    algorithm (radix sort is O(n) too).I think you assume nothing about data. In stead, you need more memory (20%) to sort using FlashSort.
    It is kind of memory for speed sorting. Here is the java code by Roseanne Zhang if you are interested:
    * FlashSort.java
    * Dr. Karl-Dietrich Neubert's Flashsort1 Algorithm
    * http://www.neubert.net/Flapaper/9802n.htm
    * Translation of algorithm into Java by Roseanne Zhang 
    * http://www.webappcabaret.com/javachina
    * Timing measurement included
    * Full functional application
    class FlashSort
        static int   n;
        static int   m;
        static int[] a;
        static int[] l;
         * constructor
         * @param size of the array to be sorted
        public static void flashSort(int size)
            n = size;
            generateRandomArray();
            long start = System.currentTimeMillis();
            partialFlashSort();
            long mid = System.currentTimeMillis();
            insertionSort();
            long end = System.currentTimeMillis();
            // print the time result
            System.out.println("Partial flash sort time     : " + (mid - start) );
            System.out.println("Straight insertion sort time: " + (end - mid) );
         * Entry point
        public static void main(String[] args)
            int size = 0;
            if (args.length == 0)
                usage();
                System.exit(1);
            try
                size = Integer.parseInt(args[0]);
            catch (NumberFormatException nfe) {
                usage();
                System.exit(1);
            FlashSort.flashSort(size);
         * Print usage
        private static void usage()
            System.out.println();
            System.out.println("Usage: java FlashSort n ");
            System.out.println("       n is integer which is the size of array to sort");
         * Generate the random array
        private static void generateRandomArray()
            a = new int[n];
            for (int i=0; i < n; i++)
                a[i] = (int)(Math.random() * 5 * n);
            //printArray(a);
            m = n/20;
            if (m < 30) m = 30;
            l = new int[m];  
         * Partial flash sort
        private static void partialFlashSort()
            int i = 0, j = 0, k = 0;
            int anmin = a[0];
            int nmax  = 0;
            for (i=1; i < n; i++)
                if (a[i] < anmin) anmin=a;
    if (a[i] > a[nmax]) nmax=i;
    if (anmin == a[nmax]) return;
    double c1 = ((double)m - 1)/(a[nmax] - anmin);
    for (i=0; i < n; i++)
    k=(int)(c1*(a[i] - anmin));
    l[k]++;
    //printArray(l);
    for (k=1; k < m; k++)
    l[k] += l[k-1];
    int hold = a[nmax];
    a[nmax]=a[0];
    a[0]=hold;
    int nmove = 0;
    int flash;
    j=0;
    k=m-1;
    while (nmove < n-1)
    while (j > (l[k]-1))
    j++;
    k = (int)(c1 * (a[j] - anmin));
    flash = a[j];
    while (!(j == l[k]))
    k = (int) (c1 * (flash - anmin));
    hold = a[l[k]-1];
    a[l[k]-1]=flash;
    flash = hold;
    l[k]--;
    nmove++;
    //printArray(a);
    * Straight insertion sort
    private static void insertionSort()
    int i, j, hold;
    for (i=a.length-3; i>=0; i--)
    if (a[i+1] < a[i])
    hold = a[i];
    j=i;
    while (a[j+1] < hold)
    a[j] = a[j+1];
    j++;
    a[j] = hold;
    //printArray(a);
    * For checking sorting result and the distribution
    private static void printArray(int[] ary)
    for (int i=0; i < ary.length; i++) {
    if ((i+1)%10 ==0)
    System.out.println(ary[i]);
    else
    System.out.print(ary[i] + " ");
    System.out.println();

  • 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.
    ¯\_(ツ)_/¯

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Array of class objects

    I was wondering how would you declare an array of class objects. Here is my situation:
    I'm working on a project dealing with bank accounts. Each customer has a specific ID and a balance. I have to handle transactions for each customer at different times, so I was thinking that I need an array of class objects; however, I dont know how to initialize them.
    Here's what I did:
    BankAccount [ ] myAccount = new BankAccount[10];
    // 10 = 10 customers
    How do I initialize the objects?
    Thankz

    I was wondering how would you declare an array of
    class objects. Here is my situation:
    I'm working on a project dealing with bank accounts.
    Each customer has a specific ID and a balance. I have
    to handle transactions for each customer at different
    times, so I was thinking that I need an array of
    class objects; however, I dont know how to initialize
    them.
    Here's what I did:
    BankAccount [ ] myAccount = new BankAccount[10];
    // 10 = 10 customers
    How do I initialize the objects?
    Thankz
    HAI
    Use the hashtable
    and store the classObject of each customer with the corresponding Id in it
    and whenever u want to recover a class match the Id and get the corresponding class
    that is the best way to solve ur problem
    Regards
    kamal

Maybe you are looking for

  • Active user List

    Hi I am using 10.1.3.4 OBIEE. How to find what are the user loged in Presentation services. e.g User1 loged in Answer page,he is looking into Dashbord 1 User2 loged in looking into Dashboard2 User3 is administrator.He want to know,what are the users

  • Playlist Created by User Auto Sync Fear

    160g classic. i set up the computer and did auto-sync. afterward, i wanted to clean up the library, so i disabled auto-sync. i have since created a playlist on the ipod and put music to it. now i want to auto-sync the ipod, but am afraid that if i do

  • Find people who wants to learn Korean

    Hi, I'm Korean college students, and I can speak Korean and English. It can be a great challenge to use skype to learn foreign language, both you and me. But if you want to talk about various topics, please contact me please. I want to learn Vietname

  • View count lost after maintenance

    I noticed that after the maintenance of yesterday, the view counts of threads are often way off. Before the maintenance I had several articles that were viewed 40K+ and 24K+ times that now show only something like 311 and 257 times. The funny thing i

  • Classic Workspace in Dreamweaver CC

    In Adobe videos about Dreamweaver CC it states we should use the Classic Workspace. However I have noticed the Classicc WS has been replaced by Compact and Expanded. How do I either bring back Classic or make a custom workspace as there is no instruc