Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7964569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T05:55:16+00:00 2026-06-04T05:55:16+00:00

In the below code, I want to understand what does the Collections.sort function is

  • 0

In the below code, I want to understand what does the Collections.sort function is doing. What does this means

Collections.sort(list, new Comparator() { a complete java function });

I understand that new Comparator() means a class object, but what is the purpose of the function block here, and what we call it in java.

Thanks.

/**
     * Sorts/shuffles the given list according to the current sending queue 
     * mode. The list can contain either Message or Tuple<Message, Connection> 
     * objects. Other objects cause error. 
     * @param list The list to sort or shuffle
     * @return The sorted/shuffled list
     */
    @SuppressWarnings(value = "unchecked") /* ugly way to make this generic */
    protected List sortByQueueMode(List list) {
        switch (sendQueueMode) {

    case Q_MODE_RANDOM:
        Collections.shuffle(list, new Random(SimClock.getIntTime()));
        break;
    case Q_MODE_FIFO:
        Collections.sort(list, 
                new Comparator() {
            /** Compares two tuples by their messages' receiving time */
            public int compare(Object o1, Object o2) {
                double diff;
                Message m1, m2;

                if (o1 instanceof Tuple) {
                    m1 = ((Tuple<Message, Connection>)o1).getKey();
                    m2 = ((Tuple<Message, Connection>)o2).getKey();
                }
                else if (o1 instanceof Message) {
                    m1 = (Message)o1;
                    m2 = (Message)o2;
                }
                else {
                    throw new SimError("Invalid type of objects in " + 
                            "the list");
                }

                diff = m1.getReceiveTime() - m2.getReceiveTime();
                if (diff == 0) {
                    return 0;
                }
                return (diff < 0 ? -1 : 1);
            }
        });
        break;
    /* add more queue modes here */
    default:
        throw new SimError("Unknown queue mode " + sendQueueMode);
    }

    return list;
}

I finally got he understanding of comparator. This simple example would help:

 Collections.sort(ls, new Comparator() 
                           {

                            public int compare(Object o1, Object o2) 
                            {
                            String sa = (String)o1;
                            String sb = (String)o2;

                            int v = sa.compareTo(sb);

                            return v;           

                                // it can also return 0, and 1
                            }
                           }    
                    );
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T05:55:18+00:00Added an answer on June 4, 2026 at 5:55 am

    The Collections.sort method sorts the collection given as the parameter. By default the natural order of the collection is used. The natural order is defined by the objects in the collection.
    For example, when you have a collection of Strings, the sort method sorts this collection in the alphabetical order of the Strings. How does the sort method knows that it has to sort alphabetically? It used the compareTo method in the String class. compareTo compares the current object (this) with another objects and decides which comes first between these two. Using compareTo on all the items in the list, sort determines the correct order.

    So compareTo determines the natural order of an object.

    What if you want some other ordering other than the natural order? Say you want to sort a list of Strings in reverse alphabetical order?

    You can do that by another (overloaded) variant of the sort method. This variant accepts a second parameter, which is a instance of the Comparator interface.

    So, you have to write your own class that implements Comparator, and so that has its own compareTo method. The sort method then uses this compareTo rather than the compareTo in the object in the collection (String).

    So you say

    class MyStringComparator<String> implements Comparator
    {
        public int compareTo(String a, String b)
        {
            return a.compareTo(b) * -1; //Reverse the order. 
                                        //The logic can be as complex as your need is
        }
    }
    

    and then

    MyStringComparator myStringComparator = new MyStringComparator();
    Collections.sort(myStringList, myStringComparator);
    

    or

    Collections.sort(myStringList, new MyStringComparator(););

    See Object Ordering

    If the MyStringComparator is going to be used only for this case, you would not want to create an separate class, give it a name, a file and so on. All you need is a something temporary that you can forget after the sort.

    So instead of writing all the code, you can say:

    Collections.sort(myStringList, new Comparator()
                                   {
                                       public int compareTo(String a, String b)
                                       {
                                           return a.compareTo(b) * -1; 
                                       }
                                   }
                   );
    

    See, the second parameter is the class definition itself.

    This is called an anonymous inner class. A kind of use and throw class, for such situations. You will see a lot of anonymous inner class in Swing event handlers.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is my below code and I want to catch the exception if any
See code below: I want Page 1 to alert #testing... This works in C
The code below does not work but meant to illustrate what I want to
I want to know how does the code below work to do because I
The code below is adapted from this answer function MessageClass() { var self =
I want to know if the below code: <?php printf (%s, $some_variable); ?> is
I want to know is below code correct ? I have following code which
Issue In the below code , say if i want to change the color
I want to send data through URL.I've tried the below code: Intent browserIntent =
I want to enable auto update script in flex3. i am using below code

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.