Results 1 to 5 of 5

Thread: Sorting objects

  1. #1
    zelenkooo is offline Member
    Join Date
    Dec 2011
    Posts
    7
    Rep Power
    0

    Default Sorting objects

    Lets say i have class Worker with property int age with getAge() public method that returns int age

    In main method i have array list type Workers with some objects of type workers .

    How can i sort list ( arraylist ) using age property ?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Sorting objects

    If you implement the Comparable<Worker> interface in your Worker class, the method Collections.sort( ... ) can do the job.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    zelenkooo is offline Member
    Join Date
    Dec 2011
    Posts
    7
    Rep Power
    0

    Default Re: Sorting objects

    great stuff
    thx

    it was easy with int ( return this.age-o.age; ) but i wounder how to implement compareTo if i would need to sort by string ( name ) for example

  4. #4
    lilezek is offline Member
    Join Date
    Jun 2012
    Posts
    23
    Rep Power
    0

    Default Re: Sorting objects

    I think String already implements Comparable so just compare them.

  5. #5
    zelenkooo is offline Member
    Join Date
    Dec 2011
    Posts
    7
    Rep Power
    0

Similar Threads

  1. Collections sorting a list made of generic class objects
    By andreiutz10 in forum New To Java
    Replies: 5
    Last Post: 02-07-2012, 06:56 PM
  2. Replies: 8
    Last Post: 08-13-2011, 07:02 PM
  3. sorting objects in java
    By nn12 in forum New To Java
    Replies: 3
    Last Post: 01-08-2011, 10:18 AM
  4. Replies: 2
    Last Post: 12-13-2010, 12:12 PM
  5. Sorting/Searching Objects with multiple types.
    By gcampton in forum New To Java
    Replies: 20
    Last Post: 10-22-2009, 12:58 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •