Using the Comparator Interface.Please Help.

Hello there,
I am trying out this example regarding the Comparator Interface.
It works fine, but I havent really understood this at all.
It deals with reverse sorting.
import java.util.*;
class MyComp implements Comparator {
public int compareTo(Object a,Object b)
String aStr,bStr;
aStr = (String)a;
bStr = (String)b;
return bStr.compareTo(aStr)
class MyComparator {
public static void main(String[] args) {
// Create a Tree Set
TreeSet ts = new TreeSet(new MyComp());
ts.add("C");
ts.add("A");
ts.add("P");
ts.add("Z");
ts.add("B");
System.out.println(ts)
Output : [Z, P, C, B, A]
I have not understood the following at all:
1) We are implementing the Comparator Interface in class MyComp.
Now where is this being called in the MyComparator class?
2) How is the reverse sorting taking place.?
How is this comparing the different instances of the MyComparator class
when I havent even instantiated the MyComparator class ?
3) How is the interface method compare To(Object a,Object b) being invoked?
Please can some please answer my questions.
Regards

class MyComp implements Comparator {
public int compareTo(Object a,Object b)
String aStr,bStr;
aStr = (String)a;
bStr = (String)b;Your reverse ordering is happening here.
If you were to write
return aStr.compareTo(bStr)
the ordering would be in normal order.
>
return bStr.compareTo(aStr)The comparator that the treeSet uses is declared and instantiated here
TreeSet ts = new TreeSet(new MyComp());
1) We are implementing the Comparator Interface in
class MyComp.
Now where is this being called in the MyComparator
or class? The comparator is being used by the TreeSet to order your entries
>
>
2) How is the reverse sorting taking place.?Explained above. For further explaination look up comparator and String.compareTo()
How is this comparing the different instances of
of the MyComparator class
when I havent even instantiated the MyComparator
or class ?Also explained above
3) How is the interface method compare To(Object
a,Object b) being invoked?Internally by the TreeSet
I hope this helped a little

Similar Messages

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • Stuck using the Comparable Interface

    I am having problems implementing the Comparable Interface in my class. I have written the compareTo method but this is not working. Can anyone see what I am doing wrong in the coding of this method. Thanks !!. (see below code for the class :
    package tma02q1;
    import java.util.*;
    This is the outline of the basic Video class.
    Such a class describes the videos stocked by a branch of a video hire company
    As well as completing the given methods you will need to make further additions
    to this class.For further details you should study the BranchTest class.
    public class Video implements Comparable {
    // declare two instance variables
    // a String to hold the video title
    // an int to hold the video rental cost - cost is held in pence
    private String aTitle;
    private int aCost;
    public Video(String aTitle, int aCost) {
    this.aTitle = aTitle;
    this.aCost = aCost;
    private void setTitle(String aTitle) {
    this.aTitle = aTitle;
    public String getTitle() {
    return aTitle;
    private void setRentalCost(int aCost) {
    this.aCost = aCost;
    public int getRentalCost() {
    return aCost;
    public String toString() {
    return "Video Title = " + aTitle + " which has a rental cost of = " + aCost;
    public boolean equals(Object vid) {
    Video arg = (Video) vid;
    return (this.aTitle.equals(arg.aTitle)
    &&this.aCost==arg.aCost);
    public int compareTo(Object vido) {
    Video arg = (Video) vido;
    int comp = aCost.compareTo(arg.aCost);
    return comp;

    You've got another serious problem with your code. Both the equals and compareTo methods will throw a ClassCastException if the parameter is not a reference to a video object. Using the instanceof operator will however solve the problem. E.g.
    public boolean equals(Object o) {
      if (o instanceof Video) {
        Video  arg = (Video) o;
        return (this.aTitle.equals(arg.aTitle)
                &&this.aCost == arg.aCost);
      else
        return false;  
    }The same approach is applicable to the compareTo method.
    Regards

  • I can't work out what apps use the internet. Please help

    I cna't work out what uses the internet and what doesn't on my iphone4 please help????

    Settings>WiFi>Off...then Settings>General>Network>Cellular Data>Off...then start launching your apps, those that require a data connection either won't work or will generate an error message. You could also accomplish the same thing by putting your phone in Airplane Mode.

  • The latest update of my IPhone 3GS has failed, now i can't use the phone. Please help.

    The latest update of my IPhone 3GS has failed, now i can't use the phone. I have tried to restore but i get a message saying 'Iphone could not be restored. An unknown error occured(6). I am running the latest version of itunes (10.4) Please help.

    Place your iPhone in manual recovery mode or DFU mode.
    1. Connect your iPhone
    2. Open iTunes
    3. Hold down the home and power button for 8 seconds. After 8 sec, let go of the power but still hold down the home button until iTunes recognize your phone in recovery mode

  • Using the  XMLAGG function.Please help.

    I am using the flwg SQL and on execution,I get displayed the error:
    [1]: (Error): ORA-06553: PLS-306: wrong number or types of arguments in call to 'SYS_IXMLAGG'My SQL Code is as follows:
    SELECT XMLELEMENT("tables:terms",XMLATTRIBUTES('http://www.tfs.com/common/tables' as "xmlns:tables"),
          XMLAGG(x.extractedcode))
          FROM (SELECT distinct xml.extract(a.xml, '/tables:term/tables:code/text()',
                xml.getns('NS_TABLES')) as extractedcode,
                xml.extract(a.xml, '/tables:term/tables:description/text()', xml.getns('NS_TABLES')) as extracteddescription
                FROM terms a
                WHERE a.ACTIVE='Y')x  Please can some one tell me what are the ERROR is?

    Difficult to tell exactly just from the query. Have you tried changing...
    XMLAGG(x.extractedcode)
    to
    XMLAGG(XMLELEMENT("tagname", x.extractedcode))
    P.S. You may be better asking XML type questions on the XMLDB forum for which the FAQ thread is here: XML DB FAQ
    Message was edited by:
    blushadow

  • Is any one knows how to find a ipad only using the serialcode? please help

    help guys ....please...

    Useful information:
    Stolen
    http://support.apple.com/kb/HT5668
    Erase iPad
    http://support.apple.com/kb/ph2701
    Lost Mode
    http://support.apple.com/kb/PH2700
    Reporting lost or stolen iPad
    http://support.apple.com/kb/HT2526

  • Since I downloaded IOS7 on my iPhone 4S, a message pop up: Password Required, enter the password for the yahoo account, every time I enter or edit a contact or use the Reminder. Please help

    Since I downloaded IOS7 on my iPhone 4S, a message popup : password required enter the password for the yahoo account, every time I edit or add contact or use reminder. Please help

    SSame here. I get the popup even when a call comes in  I have to clear the popup before I can answer..  Yahoo email is coming in just fine, so I don't even need to update password.

  • I purchased microsoft office 2011. I have downloaded and installed the software but at no time was I prompted to enter my product key. As a result I am unable to use the software. Please help me activate the software. Thanks

    I purchased downloaded and installed microsoft office 2011 onto my iMac. At no time was I prompted to enter the product key so I am unable to activate the software. Can anyone tell me what to do in order to activate the software?

    Welcome to Apple Support Communities
    Where did you download Office for Mac? If you downloaded it from Microsoft, read > http://support.microsoft.com/kb/2391941/en-us

  • Im having trouble connecting my macbookpro to the tv. im using a mini display port to hdmi adapter, when i switch tv/video to hdmi on the tv nothing pops up, and i dont have the arrangement tap on the display settings, please help!

    im having trouble connecting my macbookpro to the tv. im using a mini display port to hdmi adapter, when i switch tv/video to hdmi on the tv nothing pops up, and i dont have the arrangement tap on the display settings, please help!

    I've found that the order of operations, so-to-speak, can be important when hooking up mini display port to HDMI.  I have the most success with the following operations in this order:
    1)  Plug HDMI cable into mini displayport adapter (the cable should not be plugged into either the TV or the computer at this point)
    2)  Plug the mini displayport end of your new super-cable to the computer.
    3)  Plug the HDMI end into your TV.
    4)  Switch inputs on your TV to the proper input.
    5)  If still nothing on the TV, try a different HDMI port on your TV.
    Hopefully this helps!  Good luck.

  • When I plug my iPod into the computer, itunes won't come up on the screen and my iPod is not recognized anymore and it use to be. Please help because I can't sync it at all because it won't show up as a device

    When I plug my iPod into the computer, itunes won't come up on the screen and my iPod is not recognized anymore and it use to be. Please help because I can't sync it at all because it won't show up as a device on the right hand side of itunes.

    Try
    iOS: Device not recognized in iTunes for Windows
    I would start with              
    Removing and Reinstalling iTunes, QuickTime, and other software components for Windows XP
    or              
    Removing and reinstalling iTunes and other software components for Windows Vista, Windows 7, or Windows 8
    Before you reinstall the Apple software, also remove iCloud vi Control Panel Remove programs. The reinstall the Apple programs
    New cable and different USB port?
    Runs this and see if the results help with determine the cause
    iTunes for Windows: Device Sync Tests
    Try on another computer to help determine if computer or iPod problem

  • I have a big problem :( why is it i cant update my ipod touch 2g into ios 4! im using the latest version of itunes and everytime i click "update" it stucks on the "contacting server" please help :( i want to update it now

    i have a big problem why is it i cant update my ipod touch 2g into ios 4! im using the latest version of itunes and everytime i click "update" it stucks on the "contacting server" please help i want to update it now

    Maybe here:
    iTunes for Windows: iTunes cannot contact the iPhone, iPad, or iPod software update server

  • I know that how to convert any documents to pdf file, but don't know how to get barcode on it. I am using windows 8.1. and want to see barcode on my documents before the print. Please help.

    I know that how to convert any documents to pdf file, but don't know how to get barcode on it. I am using windows 8.1. and want to see barcode on my documents before the print. Please help.

    Hi Frank ,
    Please refer to the following link and see if this helps.
    https://helpx.adobe.com/acrobat/kb/error-organizer-database-damaged-reset-1.html
    Regards
    Sukrit Dhingra

  • I want to change my apple id password but I forgot the security questions please help me some using my icloud I'd

    I want to change my apple id password but I forgot the security questions please help me some using my icloud I'd and if confirmation is must so please phone number is mine please send a code please help me my apple

    Welcome to the Apple community.
    If you are unable to remember your password, security questions, don’t have access to your rescue address or are unable to reset your password for whatever reason, your only option is to contact AppleCare, upon speaking to an operator you should explain that your problem is related to your Apple ID, this way you will not be charged for assistance, even if you don’t have an AppleCare plan.
    The operator will take you through some steps you may have already tried, however they need to be sure they have exhausted all usual approaches before trying to reset your account, so you should try to be helpful and show patience with the procedure.
    The operator will need to verify they are speaking to the account holder and may ask you some questions that only the account holder could know, and you will need to answer them if the process is to proceed.
    Once the operator has verified your identity they will send a message through to your device which contains an alpha numeric code, which you will need to read back to them.
    Once this has been completed they will send an email to your iCloud email address after a period of 24 hours, so you should check that mail is enabled in your devices iCloud settings.
    Upon receipt of the email, use the reset link provided to reset your password, after which you should be able to make the adjustments to iCloud that you wish to do.

  • I can't connect my ipad air to my computer. It comes up with the message  'connection has timed out'. I use windows vista. Please help, I want my music catalogue on my ipad. Thanks

    I can't connect my ipad air to my computer. It comes up with the message  'connection has timed out'. I use windows vista. Please help, I want my music catalogue on my ipad. Thanks

    Have you updated your iTunes? iOS7 requires at least iTunes 11.

Maybe you are looking for

  • Publisher 2010 issue

    When I try to open a particularly large file (a book I have written with many, many pictures) I get the message that "Publisher cannot open the file." All other file of mine, of any size, will open. How do I work around this problem?

  • Dropped my iPhone in the toilet, any helpful solutions?

    dropped my iPhone in the toilet, any helpful solutions? im letting it dry out in the sun right now.

  • Is it bad for the computer to save thousands of emails?

    Hi, I have been told that it is bad for the computer to save thousands of emails... unless I somehow turn them into documents. Is this true? And if so, how would you go about doing this? I find it very useful to go back and look through emails for ce

  • New connections stop working after 31 hours of computer uptime.

    I have been using a pppoe connection since I installed archlinux in 2006. This works very well. a network cable is connected to my computer and I use it to dial a pppoe connection. I never had any problems with it. But a while ago, I thought I would

  • Can't load/install adobe reader 9.3.4

    I always get a message after the setup is completed. "Setup is interruppted...and installation is not complete" whatt's going on? would appreciate ehlp at this point. thanks.