Comparator

L

ludwig

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
 
J

jfbriere

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
 
R

Roedy Green

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

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.
 
L

ludwig

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
 
Z

zero

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

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);
}
}
 
C

Chris Smith

ludwig said:
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.

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
L

ludwig

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
 
Z

zero

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);
}
}

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top