Sort ArrayList of objects by  id

I have ArrayList of containing 'MonthlySale' objects, below is my class.
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="Month")
public class MonthlySale extends AuraDB implements Serializable, Comparable {
    private String quantity;
    private String value;
    private String avUnit;
    private int saleNumber;
    private int id;
    private String month;
    private String saleYear;
    private String description;
    private int reportNumber;
    public MonthlySale() {
    public MonthlySale(int saleNumber, String saleYear) {
        this.saleNumber = saleNumber;
        this.saleYear = saleYear;
    public MonthlySale(int saleNumber, String saleYear, int reportNumber) {
        this.saleNumber = saleNumber;
        this.saleYear = saleYear;
        this.reportNumber = reportNumber;
    @Column(name="AV_UNIT")
    public String getAvUnit() {
        return avUnit;
    public void setAvUnit(String avUnit) {
        this.avUnit = avUnit;
    @Column(name="MONTH")
    public String getMonth() {
        return month;
    public void setMonth(String month) {
        this.month = month;
    @Column(name="QUANTITY")
    public String getQuantity() {
        return quantity;
    public void setQuantity(String quantity) {
        this.quantity = quantity;
    @Column(name="SALES_NO")
    public int getSaleNumber() {
        return saleNumber;
    public void setSaleNumber(int saleNumber) {
        this.saleNumber = saleNumber;
    @Column(name="SALES_YEAR")
    public String getSaleYear() {
        return saleYear;
    public void setSaleYear(String saleYear) {
        this.saleYear = saleYear;
    @Column(name="VALUE")
    public String getValue() {
        return value;
    public void setValue(String value) {
        this.value = value;
    @Id
    @GenericGenerator(name="generator", strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name="ID")
    public int getId() {
        return id;
    public void setId(int id) {
        this.id = id;
    @Column(name="DESCRIPTION")
    public String getDescription() {
        return description;
    public void setDescription(String description) {
        this.description = description;
    @Column(name="REPORT_ID")
    public int getReportNumber() {
        return reportNumber;
    public void setReportNumber(int reportNumber) {
        this.reportNumber = reportNumber;
     public void selectMonthList() {
        hibSelectAll(this, "SELECT DISTINCT month FROM MonthlySale WHERE sales_year='" + saleYear + "' AND " +
                " sales_no = '" + saleNumber + "'");
}I want my arraylist to be ordered by id. I used collection.sort(), but i cannot sort by id.
I get objects arrayList like this way
            monthlySale = new MonthlySale(Integer.parseInt(sales_no), sales_year, 0);
            monthlySale.selectMonthList();Any help appreciated.
regards,
Dil.

Of course yes i did, like this.
public int compareTo(Object o) {
       if(this.id == ((MonthlySale)o).getId()){
            return 0;
       }else if(this.id > ((MonthlySale)o).getId()){
            return 1;
       }else{
            return -1;
    }I implement 'MonthlySale class' form Comparable interface and override above method but it doesn't work.

Similar Messages

  • Sorting ArrayList multiple times on Multiple Criteria

    I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
    I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
    private ArrayList detailsArrayList = new ArrayList( );
    // Sort arraylist using compareTo method in RaceDetail file
    Collections.sort(detailsArrayList);
    public class RaceDetail implements Comparable, Cloneable {
         public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
    public int compareTo( Object o )
         RaceDetail rd = (RaceDetail) o;
         int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
         int lastCmpA = boatNumText.compareTo(rd.boatNumText);
         int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
         int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
         int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
         int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
         int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
         // TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
         // Boat - Ascending, Second - ascending, seqNum - ascending
         return (lastCmp !=0 ? -lastCmp :
              (lastCmpC !=0 ? lastCmpC :
                   (lastCmpF !=0 ? lastCmpF :
                        (lastCmpA !=0 ? lastCmpA :
                             (lastCmpE !=0 ? lastCmpE :
                                  lastCmpD)))));
    }

    Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
    dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
    Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
    static final Comparator SORT_BY_SEQUENCE = new Comparator() {
    public int compare ( Object o1, Object o2 )
         RaceDetail rd1 = (RaceDetail) o1;
         RaceDetail rd2 = (RaceDetail) o2;
         return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 ));

  • Arraylist issue: pass all the arrayList `s object to other arrayList ...

    hi all...i hope somebody could show me some direction on my problem...i want to pass a arraylist `s cd information to an other arraylist
    and save the new arraylist `s object to a file...i try to solve for a long ..pls help...
    import java.text.*;
    import java.util.*;
    import java.io.*;
    public class Demo{
         readOperation theRo = new readOperation();
         errorCheckingOperation theEco = new errorCheckingOperation();
         ArrayList<MusicCd>  MusicCdList;
         private void heading()
              System.out.println("\tTesting read data from console, save to file, reopen that file\t");
         private void readDataFromConsole()
         //private void insertCd()
            MusicCdList = new ArrayList<MusicCd>( ); 
            MusicCd theCd;
            int muiseCdsYearOfRelease;
            int validMuiseCdsYearOfRelease;
            String muiseCdsTitle;
              while(true)
                    String continueInsertCd = "Y";
                   do
                        muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
                        muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
                        validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);
                        MusicCdList.add(new MusicCd(muiseCdsTitle, validMuiseCdsYearOfRelease));//i try add the cd`s information to the arrayList
                        MusicCdList.trimToSize();
                        //saveToFile(MusicCdList);
                        continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
                   }while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
                   if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
                                                    //MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));                              
                        break;
                      //System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
         //i want to pass those information that i just add to the arrayList to file
         //I am going to pass the arraylist that contains my cd`s information to new arraylist "saveitems and save it to a file...
         //i stuck on this problem
         //how do i pass all the arrayList `s object to another arraylist ..pls help
         //it is better show me some example how to solve thx a lot
         private void saveToFile(ArrayList<MusicCd> tempItems)
              ArrayList<MusicCd> saveItems;
              saveItems = new ArrayList<MusicCd>();
              try
                   File f = new File("cdData.txt");
                   FileOutputStream fos = new FileOutputStream(f);
                   ObjectOutputStream oos = new ObjectOutputStream(fos);
                   saveItems.add(ArrayList<MusicCd> tempItems);
                   //items.add("Second item.");
                   //items.add("Third item.");
                   //items.add("Blah Blah.");
                   oos.writeObject(items);
                   oos.close();
              catch (IOException ioe)
                   ioe.printStackTrace();
              try
                   File g = new File("test.fil");
                   FileInputStream fis = new FileInputStream(g);
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   ArrayList<String> stuff = (ArrayList<String>)ois.readObject();
                   for( String s : stuff ) System.out.println(s);
                   ois.close();
              catch (Exception ioe)
                   ioe.printStackTrace();
         public static void main(String[] args)
              Demo one = new Demo();
              one.readDataFromConsole();
              //one.saveToFile();
              //the followring code for better understang
    import java.io.Serializable;
    public class MusicCd implements Serializable
         private String musicCdsTitle;
            private int yearOfRelease;
         public MusicCd()
              musicCdsTitle = "";
              yearOfRelease = 1000;
         public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
              musicCdsTitle = newMusicCdsTitle;
              yearOfRelease = newYearOfRelease;
         public String getTitle()
              return musicCdsTitle;
         public int getYearOfRelease()
              return yearOfRelease;
         public void setTitle(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
         public void setYearOfRelease(int newYearOfRelease)
              yearOfRelease = newYearOfRelease;
         public boolean equalsName(MusicCd otherCd)
              if(otherCd == null)
                   return false;
              else
                   return (musicCdsTitle.equals(otherCd.musicCdsTitle));
         public String toString()
              return("Music Cd`s Title: " + musicCdsTitle + "\t"
                     + "Year of release: " + yearOfRelease + "\t");
         public ArrayList<MusicCd> getMusicCd(ArrayList<MusicCd> tempList)
              return new ArrayList<MusicCd>(ArrayList<MusicCd> tempList);
    import java.util.Scanner;
    import java.util.InputMismatchException;
    import java.util.NoSuchElementException;
    public class errorCheckingOperation
         public int errorCheckingInteger(int checkThing, int lowerBound, int upperBound)
               int aInt = checkThing;
               try
                    while((checkThing < lowerBound ) || (checkThing > upperBound) )
                         throw new Exception("Invaild value....Please enter the value between  " +  lowerBound + " & " +  upperBound );
               catch (Exception e)
                 String message = e.getMessage();
                 System.out.println(message);
               return aInt;
           public int errorCheckingSelectionValue(String userInstruction)
                int validSelectionValue = 0;
                try
                     int selectionValue;
                     Scanner scan = new Scanner(System.in);
                     System.out.print(userInstruction);
                     selectionValue = scan.nextInt();
                     validSelectionValue = errorCheckingInteger(selectionValue , 1, 5);
               catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return validSelectionValue;
    import java.util.*;
    public class readOperation{
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    }

    sorry for my not-clear descprtion...thc for your help....i got a problem on store some data to a file ....u can see my from demo..
    Step1: i try to prompt the user to enter his/her cd `s information
    and i pass those cd `s information to an object "MuiscCd" ..and i am going to add this "MuiscCd" to the arrayList " MusicCdList ". i am fine here..
    Step2: and i want to save the object that `s in my arrayList " MusicCdList " to a file....i got stuck here..<_> ..(confused).
    Step3:
    i will reopen the file and print it out..(here i am alright )

  • Sort table of objects by object attribute

    Hi all,
    I would like to write method for sorting table of objects. Sorting will be according selected attribute of object.
    My problem is that when I have dynamic data, I'm not able to access attributes of object. Here is example in code. Problematic lines are commented.
    If you have any idea how to solve it, I will be very happy.
    CLASS lcl_reflection DEFINITION CREATE PUBLIC.
      PUBLIC SECTION.
        CLASS-METHODS: sort_object_table_by_field IMPORTING field_name   TYPE char72
                                                            direction    TYPE c DEFAULT 'A'
                                                  CHANGING  object_table TYPE table.
    ENDCLASS.                    "lcl_reflection DEFINITION
    CLASS lcl_reflection IMPLEMENTATION.
      METHOD sort_object_table_by_field.
        DATA: obj_type_desc   TYPE REF TO cl_abap_refdescr,
              cls_type_desc   TYPE REF TO cl_abap_classdescr,
              tab_type_desc   TYPE REF TO cl_abap_tabledescr,
              elm_type_desc   TYPE REF TO cl_abap_elemdescr,
              struc_type_desc TYPE REF TO cl_abap_structdescr,
              line            TYPE REF TO data,
              tab             TYPE REF TO data,
              object          TYPE REF TO data,
              lt_component TYPE cl_abap_structdescr=>component_table,
              ls_component LIKE LINE OF lt_component.
        FIELD-SYMBOLS: <object> TYPE any,
                       <tab>    TYPE table,
                       <line>   TYPE any,
                       <value>  TYPE any.
        READ TABLE object_table INDEX 1 ASSIGNING <object>.
        cls_type_desc ?= cl_abap_classdescr=>describe_by_object_ref( <object> ).
        elm_type_desc ?= cls_type_desc->get_attribute_type( field_name ).
        obj_type_desc ?= cl_abap_refdescr=>create( cls_type_desc ).
        UNASSIGN <object>.
        ls_component-name = 'key'.
        ls_component-type = elm_type_desc.
        APPEND ls_component TO lt_component.
        ls_component-name = 'object'.
        ls_component-type ?= obj_type_desc.
        APPEND ls_component TO lt_component.
        struc_type_desc ?= cl_abap_structdescr=>create( lt_component ).
        tab_type_desc ?= cl_abap_tabledescr=>create( p_line_type  = struc_type_desc
                                                     p_table_kind = cl_abap_tabledescr=>tablekind_std
                                                     p_unique     = abap_false ).
        REFRESH lt_component.
        CLEAR ls_component.
        CREATE DATA line TYPE HANDLE struc_type_desc.
        CREATE DATA tab TYPE HANDLE tab_type_desc.
        CREATE DATA object TYPE HANDLE obj_type_desc.
        ASSIGN tab->* TO <tab>.
        ASSIGN line->* TO <line>.
        ASSIGN object->* TO <object>.
        LOOP AT object_table REFERENCE INTO object.
          APPEND INITIAL LINE TO <tab> REFERENCE INTO line.
          ASSIGN object->* TO <value>.
          ASSIGN line->* TO <line>.
    *      <line>-key = <value>->(field_name).
    *      <line>-object = object.
        ENDLOOP.
    *    SORT <tab> BY key.
    *    LOOP AT <tab> REFERENCE INTO line.
    *      APPEND INITIAL LINE TO object_table REFERENCE INTO object.
    *      object = line-object.
    *    ENDLOOP.
      ENDMETHOD.                    "sort_object_table_by_field
    ENDCLASS.                    "lcl_reflection IMPLEMENTATION

    Ok guys, it's solved. It was little bit more complicated then I expected. Thanks for you help.
    METHOD sort_object_table_by_field.
        TYPES: t_object TYPE REF TO object.
        DATA: obj_type_desc   TYPE REF TO cl_abap_refdescr,
              cls_type_desc   TYPE REF TO cl_abap_classdescr,
              tab_type_desc   TYPE REF TO cl_abap_tabledescr,
              elm_type_desc   TYPE REF TO cl_abap_elemdescr,
              struc_type_desc TYPE REF TO cl_abap_structdescr,
              r_line          TYPE REF TO data,
              r_tab           TYPE REF TO data,
              r_object        TYPE REF TO data,
              r_obj           TYPE REF TO data,
              lt_component TYPE cl_abap_structdescr=>component_table,
              ls_component LIKE LINE OF lt_component.
        FIELD-SYMBOLS: <object>    TYPE any,
                       <obj>       TYPE REF TO object,
                       <tab>       TYPE table,
                       <line>      TYPE any,
                       <key>       TYPE any,
                       <fs_key>    TYPE any,
                       <fs_object> TYPE any.
        READ TABLE object_table INDEX 1 ASSIGNING <object>.
        cls_type_desc ?= cl_abap_classdescr=>describe_by_object_ref( <object> ).
        elm_type_desc ?= cls_type_desc->get_attribute_type( field_name ).
        obj_type_desc ?= cl_abap_refdescr=>create( cls_type_desc ).
        UNASSIGN <object>.
        ls_component-name = 'key'.
        ls_component-type = elm_type_desc.
        APPEND ls_component TO lt_component.
        ls_component-name = 'object'.
        ls_component-type ?= obj_type_desc.
        APPEND ls_component TO lt_component.
        struc_type_desc ?= cl_abap_structdescr=>create( lt_component ).
        tab_type_desc ?= cl_abap_tabledescr=>create( p_line_type  = struc_type_desc
                                                     p_table_kind = cl_abap_tabledescr=>tablekind_std
                                                     p_unique     = abap_false ).
        REFRESH lt_component.
        CLEAR ls_component.
        CREATE DATA r_line TYPE HANDLE struc_type_desc.
        CREATE DATA r_tab TYPE HANDLE tab_type_desc.
        CREATE DATA r_object TYPE HANDLE obj_type_desc.
        CREATE DATA r_obj TYPE REF TO object.
        ASSIGN r_tab->* TO <tab>.
        LOOP AT object_table REFERENCE INTO r_object.
          APPEND INITIAL LINE TO <tab> REFERENCE INTO r_line.
          ASSIGN r_object->* TO <object>.
          ASSIGN r_obj->* TO <obj>.
          MOVE <object> TO <obj>.
          ASSIGN <obj>->(field_name) TO <key>.
          ASSIGN r_line->* TO <line>.
          ASSIGN COMPONENT 'KEY' OF STRUCTURE <line> TO <fs_key>.
          ASSIGN COMPONENT 'OBJECT' OF STRUCTURE <line> TO <fs_object>.
          <fs_object> = <object>.
          <fs_key> = <key>.
        ENDLOOP.
        DATA: sort_field TYPE fieldname.
        sort_field = 'KEY'.
        SORT <tab> BY (sort_field).
        REFRESH object_table.
        LOOP AT <tab> REFERENCE INTO r_line.
          APPEND INITIAL LINE TO object_table REFERENCE INTO r_object.
          ASSIGN r_line->* TO <line>.
          ASSIGN r_object->* TO <object>.
          ASSIGN COMPONENT 'OBJECT' OF STRUCTURE <line> TO <fs_object>.
          <object> = <fs_object>.
        ENDLOOP.
      ENDMETHOD.

  • LINQ sorting on List Object - Various Object Type

    I try to sort a List<Object> where the Object are different classes but all share the same Property Name for instance.
    I got a Base Class where Class A and Class B inherit from the Base Class.
    So during the Linq query I cannot specify with object type this is.
    Problem here "from ?????Entry_Global?????? list in Entries"
    Thanks for helping.
    ////Entries is a List<Object> which consist of class object as following\\\\\
    public abstract class EntryBase<T>
    private string _Name;
    public string Name
    get { return this._Name; }
    set { this.SetProperty(ref this._Name, value); }
    public class Entry_Global : EntryBase<Entry_Global>
    public class Entry_CC : EntryBase<Entry_CC>
    private string _url; //Web url
    public string Url
    get { return this._url; }
    set { this.SetProperty(ref this._url, value.Contains("http") ? value : "http://" + value); }
    public List<Object> SortBy()
    IEnumerable<KeyedList<string, object>> groupedEntryList = null;
    //The proble reside in the fact that list is not only one type
    //so when comes in the orderby "Name" it doesn't know Name
    //or any other properties which are all common to all those class
    //It does not want to convert Entry_CC or Entry_Global to EntryBase
    groupedEntryList =
    from ?????Entry_Global?????? list in Entries
    orderby list.Name
    orderby list.CategoryRef.Name
    group list by list.CategoryRef.Name into listByGroup
    select new KeyedList<string, object>(listByGroup);
    return groupedEntryList.ToList<object>();

    Entry_Global and Entry_CC don't share the same base class since EntryBase<Entry_Global> and EntryBase<Entry_CC> are two totally different types so you cannot cast the objects in the List<object> to a common base class in this case.
    You could cast from object to dynamic though:
    public List<Object> SortBy()
    List<object> objects = new List<object>();
    objects.Add(new Entry_Global { Name = "K" });
    objects.Add(new Entry_CC { Name = "A" });
    objects.Add(new Entry_Global { Name = "I" });
    objects.Add(new Entry_CC { Name = "C" });
    var sortedObjectsByName = (from o in objects
    let t = (dynamic)o
    orderby t.Name
    select o).ToList();
    return sortedObjectsByName;
    The dynamic keyword makes a type bypass static type checking at compile-time:
    https://msdn.microsoft.com/en-us/library/dd264736.aspx. This basically means that a dynamic type is considered to have any property of any name at compile time. Of course you will get an exception at runtime if the type doesn't have a Name property but
    providied that all objects in the List<T> to be sorted are of type EntryBase<T> you will be safe as long as the EntryBase<T> type defines the Name property that you sort by.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Sorting ArrayList

    Hi to all,
    I have to sort ArrayList elements in alphabetical order.When i tried to do with the following code iam getting "java.lang.ClassCastException:".
    List lStyleArray = new ArrayList();
    lStyleArray =(ArrayList)xxx.getxxx();
    Collections.sort(lStyleArray );
    Could anybody help to overcome this problem.Thanks in advance

    Presumably, "xxx.getxxx()" is returning something that is not an ArrayList.
    So you have to fix that, or change what you're trying to do. Maybe it's a List other than an ArrayList. You don't need to cast it to be an ArrayList specifically, probably.
    Also are you aware that on the first line, you're creating an ArrayList and then immediately throwing it away?

  • How to Sort ArrayList

    Hi
    I have class like below , i store them in a ArrayList, is it possible to sort this ArrayList by name or by date.
    The class is as below
    public class MyInfo
    private String name;
    private Date date;
    //have getters and setters for name and date
    ArrayList data = new ArrayList();
    data.add(instance of MyInfo)
    Ashish

    Comparable doesn't really apply here IMO, since he
    uses different ordering criteria - name and date.Did you read the link? The tutorial contains useful information on the Comparator as well as the Comparable interface, which is why I posted it. I believe you're objecting only to the title of the article.
    :o)

  • Collecstions.sort(ArrayList) - Please Explain

    Hello,
    This is a rewrite of an earlier question. Hopefully, I better formed the question in this post.
    Can anyone explain why the first code example requires that I write a compareTo() method (called by Collections.sort(bidList)) and a toString() method (called by System.out.println(bidList), while the second code example requires no such additional code in my program?
    Thanks for all responses.
    Karl
    First Code Example (Requires comparTo() and toString() methods in the program.)
         public static void main(String[] args) {
            // fill a list with 5 bids
            ArrayList bidList = new ArrayList();
            for(int i=0; i<5; i++){
                //generate random number 0-100 for a bid amount
                bidList.add(new AuctionBid("Bidder" + i, (int)(Math.random()*100)));
            //sort the bids in natural order and display them
            Collections.sort(bidList); //Why does this call method compareTo()
            System.out.println("Natural order sort by bid amount");
            System.out.println(bidList); //Why does this call method toString()
    }Second Code Example (Does not require compareTo() or toString() methods in the program.)
            public static void main(String[] args) {
            // fill a list with 5 bids
            System.out.println("Printing bidList from Array: ");
            String[] bidList = new String[5]; 
            for(int i=0; i<5; i++){
                if(i==0){bidList[i] = "Zoey";}
                else if (i==1){bidList[i] = "Megan";}
                 else if (i==2){bidList[i] = "Larrry";}
                  else if (i==3){bidList[i] = "Brian";}
                   else if (i==4){bidList[i] = "Abigail";}
       List list2 = Arrays.asList(bidList); // Does NOT requre a toString() method to be coded.
       System.out.println("Printing Unsorted list2: ");
       System.out.println(list2);
       Collections.sort(list2); // Does NOT require a compareTo() method to be coded.
       System.out.println("Printing Sorted list2: ");
       System.out.println(list2);
    }

    To answer your first question, Collections doesn't
    know how to sort any ArrayList unless the objects
    implement the Comparable interface and define the
    compareTo method. The String class already defines
    the compareTo method for you, and that's why your
    second ArrayList doesn't require you to write one.
    In your first list you're loading AuctionBid
    references, and Collections can't sort that list
    unless your AuctionBid class implements Comparable
    and defines the compareTo method.
    To answer your second question, System.out.println
    calls toString on the object reference you pass to
    it, unless the reference actually IS a String
    reference. How else could it get a string
    representation of an object without calling toString
    on it?Thank you!
    That makes sense.
    Karl

  • Sort ArrayList on multiple values

    Hi all!
    i'm trying to sort an ArrayList that contains a list of beans with a bunch of properties.
    i think that the comparator should be written like this:
        protected class CategoryComparator implements Comparator {
            public int compare(Object o1, Object o2) {
                Category cat1 = (Category)o1;
                Category cat2 = (Category)o2;
                return cat1.getCategoryName().compareTo(cat2.getCategoryName()) & cat1.getCategoryId().compareTo(cat2.getCategoryId());
        }where Category is the bean, getCategoryName and getCategoryId return two strings. Is that right to get the list sorted on both the two fields?
    Thanks!

    No, it's not. Assuming categoryName is of higher priority, you want int comp = cat1.getCategoryName().compareTo(cat2.getCategoryName());
    if (comp != 0) return comp;
    return cat1.getCategoryId().compareTo(cat2.getCategoryId());

  • Sort arrayList for integer

    hi,
    some doubts on the syntax
    rows.add(String.valueOf(destList));is this the correct syntax eventhough my "destList" is an integer?
    Collections.sort(rows);i would like to sort my arrayList but it doesnt seem to work with this syntax.the values in my arraylist are in integer.
    please help.thanks

    Maybe a little off topic, but this might be of interest to anyone that wants to sort a 2 dim object array (Object[][]).
    As part of the formatteddataset open source API I have a utility class called ArraySQL. It allows you to issue a reduced sql syntax against an array (i.e. specify a column list, where and order by clauses). The basic idea is that because a 2 dim Array is conceptually similar to a db table you could be able to query it. I will be releasing on sourceforge in a couple weeks, but in the meantime if anyone is interested i can send it to them. Here are some examples
    import com.fdsapi.arrays.ArraySQL;
    Object[][] data{
          {"jim","smith", new Integer(200)}, 
          {"jeff","souza", new Integer(500)},
          {"jim","anderson", new Integer(100)},
          {"stan","jones",new Integer(2000)}};
    ArraySQL asql=new ArraySQL("select * from array where col0 in ('jim', 'jeff') order by col0 asc, col1 desc")
    Object[][] newData=asql.execute(data);
    asql=new ("select * from array order by col2 desc");
    newData=asql.execute(data);steve -
    http://www.fdsapi.com - An easy, fast, extensible way of generating xml and html
    http://www.jamonapi.com - An easy way to monitor application code.
    Both tools are open source and available for download on the given sites.

  • Sorting ArrayLists

    How can you sort an ArrayList in ascending order without using the following line of code?
    Collections.sort(myArrayList);I've come up with a bit of code so far, but I have an error message that says "incompatible types" for the two lines that define variables first and second. The code is supposed to be able to sort the ArrayList called "list" in ascending order, and save it into an ArrayList called "list2"... except I can't use that wonderful line of code I mentioned earlier that makes life so much darned easier. The code I'm posting is just the horrible code I have so far for the method that should sort it... all ArrayLists, etc. have been defined and all that good stuff. Any help would be greatly appreciated.
    public static void sorter()
              int count=1;
              list2.add(list.get(0));
              for(int i=0; i<list.size(); i++)
                   for(int f=0; f<list2.size(); f++)
                        int first=list.get(count);
                        int second=list2.get(f);
                        if(first<second)
                             list2.add(0,list.get(count));
                             break;
         }

    Assuming the array holds Objects, you can't just assign them to an int. Try:    // with autoboxing
    // int first=(Integer)list.get(count);
        // without
    int first=((Integer)list.get(count)).intValue();[Edit]Indeed with autoboxingfor(Integer i=0;  // etc...

  • How to pass arraylist of object from action class to jsp and display in jsp

    I need to do the following using struts
    I have input jsp, action class and action form associated to that. In the action class I will generate the sql based on the input from jsp page/action form, create a result set. The result set is stored as java objects in a ArrayList object.
    Now I need to pass the arraylist object to another jsp to display. Can I put the ArrayList object in the request object and pass to the success page defined for the action? If this approach is not apprpriate, please let me know correct approach.
    if this method is okay, how can I access the objects from arraylist in jsp and display their property in jsp. This java object is a java bean ( getter and setter methods on it).
    ( need jsp code)
    Can I do like this:
    <% ArrayList objList = (ArrayList)request.getattribute("lookupdata"): %> in jsp
    (***I have done request.setattribute("lookupdata", arraylistobj); in action class. ***)
    Assuming the java object has two properties, can I do the following
    <% for (iint i=0. i<objList.size;I++){ %>
    <td> what should i do here to get the first property of the object </td>
    <td> what should i do here to get the first property of the object </td>
    <% }
    %>
    if this approach is not proper, how can I pass the list of objects and parse in jsp?
    I am not sure what will be the name of the object. I can find out how many are there but i am not sure I can find out the name
    thanks a lot

    Double post:
    http://forum.java.sun.com/thread.jspa?threadID=5233144&tstart=0

  • How to Sort Array of Object

    Hallo. I have an array of objects. Each object has id and name. How can i sort by name or by id??
    Thx for all
    Max

    array.sortOn("name");

  • CS3: elements sorting of selection object

    Hi people!
    I think U know that in CS2 app.selection[0] always return LAST selected object
    and app.selection[app.selection.length] return FIRST selected object
    its logically good way.
    but in CS3 Adobe changed this order. And now sorting of objects in this array depend not from selection order.
    now question: how to determine the first and last selected object in CS3?
    Му collection of cs2 scripts be based on this behoviour.
    Did anybody know how to solve this problem. May be exist simple way via javascript? Or harder - via third party plugins...
    Help please!

    >now question: how to determine the first and last selected object in CS3?
    Unfortunately, you can no longer do that in CS3. I don't know of any workarounds.
    Peter

  • Pass an ArrayList of objects from C++ to JAVA using JNI

    Hello,
    I need to get the running Windows processes using C++ and have a Process struct in C++ having 2 fields: name and pid. I want to pass an ArrayList of Process from C++ to Java. I have found an example of how to pass an array of objects from C++ to Java, but I'd like to pass an ArrayList, and I was wondering if this is possible, before understanding that example and use an array.
    I don't have much experience with C++ and I don't even know if you have something like an ArrayList in C++, so I'm sorry if it doesn't make any sense what I'm talking about. Thank you.

    From C you can access and/or imnstantiate one of the
    java collections. In other words, your C code should
    simply populate java structures and a collection.I have read this is possible after I posted this, but didn't find an example yet. I began reading "Java Native Interface" book from Addison-Wesley today to get a better understanding of JNI.
    If you know where to find an example of doing this, I would appreciate it. Otherwise, I suppose I will find this in the above mentioned book quite soon... Thank you.

Maybe you are looking for

  • Currency Symebol in output Report

    Hi, We have a requirement for showing currency symbol in out put of the report.I need a report for values of revenue with indian currency symbol while displaying the output. Thanks in advance.

  • Safari in v 10.5.8 keeps crashing on launch

    Hi, hoping someone may be able to help. Safari (latest v. for Leopard) keeps crashing after a few seconds of it being launched. The last thing I did was run Onyx. I have tried various things mentioned in other posts i.e. went to clear InputManagers b

  • "Press Esc to boot..." countdown

    First time post, so let me say hi to you all! This may sound like a bit of a simple question... As my signature says I have a MSI P45 Neo3-F motherboard. I'm really happy with it, but I have one small niggling problem (if you can call it a problem)..

  • DTW Failing to Update Pricing

    Hi, I updated pricing for a particular price list for a bunch of items using the DTW but not all have updated. The log from the DTW reported all were successful, but about 10% of items didn't change.  The template is definitely correct as I have done

  • Help in pagination w/ save feature

    hi, can somebody help me with my jsf code. basically this code displays inputText in tabular view and is paginated. The problem is when i press the save button. <h:form>                 <h:dataTable value="#{catsh.all}" var="cat" id="pager" rows="3">