Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

Comparator

Thread view: 
ludwig - 02 Dec 2005 22:28 GMT
Hi, I try to write my own comparator for sorting TreeMap, but all my
experiments failed. The constructor TreeMap(Comparator c) as described
in books and tutorials doesn't recognize my interface, although I tried
every combination I could think of. Could anybody help?
I also hoped to find the original comparator, which makes the "natural
order" sorting, because I could use it with only some small changes,
but I didn't find it. Is it accessible? Thanks
Roedy Green - 02 Dec 2005 22:47 GMT
>I also hoped to find the original comparator, which makes the "natural
>order" sorting, because I could use it with only some small changes,
>but I didn't find it. Is it accessible? Thanks

see http://mindprod.com/jgloss/comparator.html
for lots of source code examples.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

George Cherry - 02 Dec 2005 22:56 GMT
>>I also hoped to find the original comparator, which makes the "natural
>>order" sorting, because I could use it with only some small changes,
>>but I didn't find it. Is it accessible? Thanks
>
> see http://mindprod.com/jgloss/comparator.html
> for lots of source code examples.

It just occurred to me that you have a heck of a lot of
Java info at  http://mindprod.com, and I wondered what
I'd get if I Googled

java comparator

Sure enough, your site's link was third from
the top of 268,000 pages. Congratulations!
(java.sun.com was first, of course.)

George
Roedy Green - 02 Dec 2005 23:34 GMT
On Fri, 2 Dec 2005 17:56:12 -0500, "George Cherry"
<GWCherryHatesGreenEggsAndSpam@alum.mit.edu> wrote, quoted or
indirectly quoted someone who said :

>It just occurred to me that you have a heck of a lot of
>Java info at  http://mindprod.com, and I wondered what
[quoted text clipped - 7 lines]
>
>George

I have wondered about why Google gives me such high ranks. I
hypothesise:

1. someone at Google shares my anti-war sympathies and nudged
something with her elbow to bump my ranks.

2. Glossary entries have <DT> in them.

3. Glossary entries tend to be about one thing.  They are very
condensed in related keywords to that official topic.

4. My glossary entries link to other famous entries on the topic.
E.g. most entries about Sun classes have links to the Sun JavaDoc both
locally and on the web.

5. Google looks through people's web-based bookmark pages.  There are
a number of reference pages in the Java glossary like
http://mindprod.com/applets/fileio.html
http://mindprod.com/applets/conversion.html
http://mindprod.com/jgloss/unicode.html
http://mindprod.com/jgloss/gotchas.html
http://mindprod.com/jgloss/unmain.html
Google ranks pages higher the more links there are to them.

6. SlashDot and Sun have links to my pages. In the Google world, who
links to you carries great prestige.

7. Google may be looking at all my references in the Java newsgroups
as if they were independent web references.

8. I don't do anything at all to artificially raise my ranking.
Perhaps everyone else is getting penalty points for cheating.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

jfbriere - 02 Dec 2005 23:01 GMT
What does not work?
You say you have implemented the java.util.Comparator interface
(http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html)
and then passed an instance of it to the
java.util.TreeMap(java.util.Comparator) constructor,
then what? Does it compile? Does it run? What happens? Please be more
specific.

Also, there is no "original" Comparator.
The TreeMap instanciated without any Comparator uses the natural
ordering of its keys,
meaning that the keys must implement the java.lang.Comparable interface
(like java.lang.String, java.lang.Integer, ...) and then call
Comparable.compareTo() with the keys.

Regards
ludwig - 03 Dec 2005 09:53 GMT
Hi, I made "public interface myComparator extends Comparator" and added
signatures of two methods compare(Object, Object) and equals(Object).
This compiles. Then I created new class, where I use TreeMap trm = new
TreeMap() etc. I fill the map and it sorts keys in natural order. This
compiles and works. My goal is, however, to make some slight changes in
sorting. For that purpose I added methods compare and equals with body
and changed TreeMap trm = new TreeMap(myComparator). This doesn't
compile with error message "cannot resolve variable myComparator". I
made also dozens of other combination, but after a week I have the
impression of making trial and error in the dark. Obviously I lack some
basic knowledge.
Thanks a lot
regards
ludwig
zero - 03 Dec 2005 13:41 GMT
"ludwig" <sci@onthenet.ch> wrote in news:1133603628.290761.104400
@g47g2000cwa.googlegroups.com:

> Hi, I made "public interface myComparator extends Comparator" and added
> signatures of two methods compare(Object, Object) and equals(Object).
[quoted text clipped - 10 lines]
> regards
> ludwig

listen to your compiler: it says it cannot resolve the variable
myComparator, which means myComparator is not defined before you use it.  
Make sure that 1. it is defined before it's used 2. it's spelled
correctly (capitalization matters) and 3. it's of the right type.

Also note that interface and class names should start with a capital
letter, variables should not.

Finally, make sure you understand the difference between an interface (or
class) definition and a variable definition.  A variable is an *instance*
of a class (or interface, in some cases).

you probably have something like this:

public interface myComparator extends Comparator
{
  // ...
}

class TestClass
{
  public static void main(String args[])
  {
     new TreeMap(myComparator);
  }
}

mistakes:
- myComparator should be MyComparator
- myComparator is an interface name, not a variable
- myComparator is not a class, hence no objects of type myComparator can
exist (there are exceptions, but for now just remember you can have
instances of a class, not of an interface)

Correct would be:

public class MyComparator implements Comparator
{
  // implementation of compareTo()
}

class TestClass
{
  public static void main(String args[])
  {
     MyComparator myComparator = new MyComparator();
     new TreeMap(myComparator);
  }
}

Signature

Beware the False Authority Syndrome

ludwig - 04 Dec 2005 15:39 GMT
Hi Zero
thanks a lot for the help, I used your advice in the form
public interface myComparator extends Comparator
{
  // ...
}
class TestClass
{
  public static void main(String args[])
  {
    TreeMap myMap = new TreeMap(myComparator);
  }
}
and it is working. However, I feel somewhat confused:
-    The constructor for TreeMap prescribes explicitly TreeMap(Comparator
c). myComparator is not formally a Comparator, it is an instance of a
class. This class could do a lot of other things and perhaps have more
implemented interfaces. (Is it so?) Java compiler is usually very
strict about the exact form of arguments, so I am surprised that it
takes something for a comparator, if "served on a plate of a
class".
-    Interface cannot be instantiated. But there seems to exists some
hidden form of instance, since the method myMap.comparator() returns a
concrete  comparator, which sounds to me very much like an instance.
-    I appreciate very much the ability of Java compiler to recognize a
comparator (which is per definition an interface) in the instance of a
class, but don't know, how much I can generalize this for other
applications. Does a class with more implemented interfaces live
multiple life and shows "multiple faces" to the compiler? Again,
this is a very admirable ability.
I am afraid, that I don't think sufficiently "Java" yet. (I
program since 15 years in G2 and am a greenhorn in Java). I would
appreciate your comment. Thanks again.
regards
ludwig
zero - 04 Dec 2005 16:14 GMT
> Hi Zero
> thanks a lot for the help, I used your advice in the form
[quoted text clipped - 9 lines]
>    }
> }

Um no that is what you had, not what I suggested.  If it's working I
guess you just mis-quoted :-)

> and it is working. However, I feel somewhat confused:
> -     The constructor for TreeMap prescribes explicitly
> TreeMap(Comparator c). myComparator is not formally a Comparator, it
> is an instance of a class. This class could do a lot of other things
> and perhaps have more implemented interfaces. (Is it so?)

yep that's correct.

> Java
> compiler is usually very strict about the exact form of arguments, so
> I am surprised that it takes something for a comparator, if "served on
> a plate of a class".

Well the thing to understand here is that an instance of a subclass *is
an* instance of a superclass.  A classical example:

class Car { ... }
class Mercedes extends Car { ... }

Here Mercedes *is a* Car.  This means that everywhere where the compiler
expects a Car object, you can use a Mercedes instead, and it won't
complain.
The same goes for interfaces.  MyComparator *is a* Comparator.

> -     Interface cannot be instantiated. But there seems to exists some
> hidden form of instance, since the method myMap.comparator() returns a
> concrete  comparator, which sounds to me very much like an instance.

There are actually two ways to do this: create an object of a class that
implements the interface, and send that back (see above, it is an
instance of the interface, as well as of the class), or create an
anonymous class that implements the interface.  This is in fact the same
as creating a normal class, it just looks different.  And this is
probably the way it's done in TreeMap:comparator().

For example:

public Comparator comparator()
{
 return new Comparator()
   {
     public int compareTo(Object o)
     {
       return 0;
     }
   };
}

This looks like a Comparator is being instantiated - but in fact this
creates a class with no name that implements the Comparator interface.
Try looking for "anonymous class" online if you want a more complete
explanation.

> -     I appreciate very much the ability of Java compiler to recognize
> a comparator (which is per definition an interface) in the instance of
> a class, but don't know, how much I can generalize this for other
> applications. Does a class with more implemented interfaces live
> multiple life and shows "multiple faces" to the compiler? Again,
> this is a very admirable ability.

Pretty much yes.  If you have a class like this:

class MyClass extends BaseClass implements Interface1, Interface2
{
  // ...
}

then objects of this class are instances of MyClass, BaseClass,
Interface1, Interface2, plus any classes that BaseClass inherits from,
and any interfaces any of those base classes implement.  So yes an object
of type MyClass has a lot of faces to show the compiler, as you said :-)

Btw all objects are also instances of class Object, even if you don't
explicitly extend Object.

> I am afraid, that I don't think sufficiently "Java" yet. (I
> program since 15 years in G2 and am a greenhorn in Java). I would
> appreciate your comment. Thanks again.
> regards
> ludwig

Practice :-)  And get a good book about Object Orientation.  Your
questions are not really specific to Java (though the details are), they
are fundamental OO concepts.  One possibility is UML 2 Toolkit by
Eriksson, but there are many others.

Signature

Beware the False Authority Syndrome

Chris Smith - 03 Dec 2005 21:38 GMT
> Hi, I made "public interface myComparator extends Comparator" and added

> and changed TreeMap trm = new TreeMap(myComparator). This doesn't
> compile with error message "cannot resolve variable myComparator".

Get a good book on Java.  Bruce Eckel's is wordy, but decent.

The problem here is that myComparator isn't a variable.  It's a class.  
The two are so different that most people reading this thread haven't
even noticed that you are trying to use one when the other is required.

It would also help if you followed standard naming conventions.  For
example, call your interface MyComparator, rather than myComparator.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.