Results 1 to 3 of 3
  1. #1
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    262
    Rep Power
    2

    Default About using the Comparator with ArrayList

    My goal is to sort an ArrayList by a data field of the objects inside, an integer. After reading about the comparator and comparable
    and seeing some examples I applied it to my classes, but I am not sure if it is correct.

    Java Code:
    public class Task implements Comparator<Task>
                 ......
                 @Override
                 public int compare(Task t1, Task t2) {
    	         return t1.priority - t2.priority;
                 }
    In another class where tasks is 'ArrayList<Task> tasks;'

    Java Code:
    public void sortTasks() {
    	     Collections.sort(tasks, new Task());
             }
    Does it work?
    and also, why in the sort method must be passed a new object of the type? Is it the comparator?

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

    Default Re: About using the Comparator with ArrayList

    Why not make the Task class implement the Comparable<Task> interface; you won't need that second (Comparator) object for the sort( ... ) method ...

    kind regards,

    Jos

    ps. any class could've implemented the Comparator<Task> interface; you have to pass an object of that class to the two-argument sort( ... ) method.
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    262
    Rep Power
    2

    Default Re: About using the Comparator with ArrayList

    Nice, I did just that.

Similar Threads

  1. Replies: 12
    Last Post: 07-07-2011, 08:49 PM
  2. Comparable and Comparator
    By jeanjiang in forum New To Java
    Replies: 7
    Last Post: 04-23-2011, 07:59 AM
  3. how to use comparator
    By KidneyinaCooler in forum Advanced Java
    Replies: 2
    Last Post: 07-18-2010, 10:25 AM
  4. How to search with a Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 PM
  5. How to write your own Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:38 PM

Posting Permissions

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