File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Question On Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question On Comparator" Watch "Question On Comparator" New topic
Author

Question On Comparator

Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
I am beginneer and finding it difficult to solve below question.......

Write a program that sorts some objects using a Comparator. Assume that the objects to be sorted belong to a class called Shape. Sort the objects in ascending order of the x co-ordinate of their origin.
1. Define the Shape class.
2.Assume that it has a constructor of the form Shape(int x , int y) and a method int getX().
3.Define the Comparator class and write the sorting program which creates some Shape objects and sorts them
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Start with the simplest thing you can think of. For example, could you write a Shape class to make this work?

You could put those two lines in the main() of Shape just to get started. Try something just that small and show us what you made ... even if it doesn't work. That way we get to know you and you get to know the solution a little at a time.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
But then how to add program to sort shapes using comparator. Actually I did not understand the question.
Secondly as they are saying that define shape class does it mean that we have to write as follows;
Shape{
Shape();
Shape(int x, int y);
getX();
}

Shape(int x, int y){
?? Donot know what to do?
}
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I realized just after I posted that I forgot to ask you to trust us ... sorting will come along when needed.

Yes, you'll need to make a class with signatures very much like what you showed. Let's cut them back for now to just the bare minimum. A constructor with x & y would be a good start:

I added "member variables" called x & y to hold the location, and initialized them in the constructor. Since this is the only constructor, we can be sure they are properly initialized in any Shape instance.

Now you can do "Shape s = new Shape(1,1)" Can you fill in the getX() method?
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Ok it is like this
public class Shape
{
private int x;
private int y;

public Shape( int newX, int newY )
{
x = newX;
y = newY;
}
public int getX()
{
return 1// not sure which int ?
}

}

Secondly is it that we should add one default constructor in this code.
About sorting using comparator I donot know.
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
You're going to have to do something on your own. You were given a basic Shape class and asked to just do the getter method for x. And this is the best you can come up with?



Not sure which int? Well the name of the method is getX so, and maybe it's just me, but I wouldn't return the y, which leaves you with one option!

Forget about the comparator for the moment and concentrate on learning to write a simple class, and simple getter/setter method. Once you've done that you can move on to the harder part.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

SECOND WARNING

"moni moni"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark
[ July 21, 2005: Message edited by: Mark Spritzler ]

Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Hi Moni,

you also want to realize that we want to help you very much, and want you to be able to solve it, without giving you the answer right out the bag. Most of the time, questions like these are homework. An assignment given to you at school. So we can't give you the answer, because that would be considered cheating.

OK, so think about the question. You have a Shape, so it might end up being a Circle or Square. And you will have to tell it where to put it. So like in math, there is an x and y axis to allow us to state a point (x, y) where it will be drawn from.

Do you remember the (x,y) coordinate system from geometry?

There is a special component of Object Oriented Programming called Encapsulation. What this means is that the instance variables are private and the only means of getting to those values from outside the class is through getters and setters, or sometimes called accessor methods. In Java these type classes follow the JavaBeans convention. Which is all instance variables are declared private (could be protected, but lets make this easy). And that all getter and setter methods have the following format.

getXXXX() and setXXXX() where the XXXX is the exact name of the instance variable it is accessing. So we could have a class Person which has a first and last name. Kind of like our naming policy, hint hint .

so the class would look like this



Now I didn't put in the getter and setter for lastName because I am lazy. But they would also have to be in there.

So, back to the code. In the getFirstName method, why did I return firstName and not lastName. Simple because of the name of the method.

Does that make sense?

Now for the Comparator or Comparable, we are going to make you do some extra work. We are going to show you how to use the Java API Javadocs. If you haven't downloaded the documentation for Java, you can do it at java.sun.com.

Go there and find the Comparable interface and read the beginning part that explains what a Comparable is, and report back to us.

Good Luck

Mark
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Thanks mark,
I will give a try for the Comparator using Java API.
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Comparable is an interface in java.lang which gives the total ordering of objects. It has method compareTo().
Kindly have a look for this try of comparator class and sorting the shape objects.

// To define Shape objects class for comparision
public class ShapeComparasion
{
Shape s1 = new Shape(1,1);
Shape s2 = new Shape(2,2);
if ( s1.compareTo(s2)==0)
{
//?
}
// How to sort ?
}
Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
The big question is: What makes one Shape less than, equal to, or greater than another Shape?
You can't implement the Comparable interface until you make that decision.

A class implementing the Comparator interface has a compare method, which takes 2 Object parameters.
Here's an example of a custom Comparator that compares 2 Person objects:

import java.util.*;

public class ComparatorExample
{
class PersonComparator implements Comparator
{
public int compare(Object p1, Object p2)
{
return ((Person)p1).compareTo((Person)p2);
}
}

static ArrayList a1 = new ArrayList();
public static void main(String[] args)
{
Person p1 = new Person("Ajay", "Female");
Person p2 = new Person("Kedar", "Male");
Person p3 = new Person("Amit", "Male");
a1.add(p1);
a1.add(p2);
a1.add(p3);
Comparator comp = new ComparatorExample().new PersonComparator();
Collections.sort(a1, comp);
System.out.println(a1.toString());
}

}
In the above example, the Person objects in the ArrayList would be sorted based on my custom Comparator.
BTW, the compareTo method in my bean class sorts the Person objects based on the second character of the names of the Person objects.
Hope you can figure out the code from here on for your example.

[ July 22, 2005: Message edited by: Kedar Dravid ]
[ July 22, 2005: Message edited by: Kedar Dravid ]
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
The big question is: What makes one Shape less than, equal to, or greater than another Shape?
You can't implement the Comparable interface until you make that decision.

That answer is in the first post, it's according to the x coordinate!

Moni, (trying to be as nice as possible here) you still have to demonstrate a few things before we (or at least I) spoon feed you the answers.

The first thing, and I'm joking just a little bit here but also a little serious. If you can't manage to understand and get the naming policy right what chance do you have being a programmer? All you had to do was add a second letter or two to your last name of 'M' and it probably would have been okay.

Second, you never answered the question of whether you understood the getter/setter methods. If you don't understand those yet I (and I'm guess some others) aren't going to waste our time trying to explain comparator. I wouldn't try to teach algebra to someone who's doesn't yet know addition and subtraction.

I'm really not trying to be mean here and would love to help, but so far this thread comes off as a "do my homework for me" type of thing, with you unwilling to do much on your own.
[ July 22, 2005: Message edited by: Hentay Duke ]
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Hello Hentay Duke,

Actually I never use my surname. I am mostly identified by first name . But still If u want to know it is Moni Marva.

Secondly I understood the concept of getter and setter and hence I shifted to the part 2 of the question. Thanks for that . Infact thanks to all who are helping me and making Java so simple. Now I am trying comparator and will get back if i have some more doubts.

Thanks to "Kedar Dravid " as well.
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
First of all thanks to all (Stan James, Hentay Duke, Mark Spritzler, Kedar Dravid) who have given the valuable inputs,

Here I have tried for the solution of Comparator of the Shape class; as demonstrated in the PersonComparator Class

import java.util.*;

public class ComparatorExample
{

class ShapeComparator implements Comparator
{

public int compare(Object obj1, Object obj2)
{

return ((Shape)obj1).compareTo((Shape)obj2);
}
}


static ArrayList a1 = new ArrayList();

public static void main(String[] args)
{

Shape shapeObj1 = new Shape (10,20);
Shape shapeObj2 = new Shape (30,40);
Shape shapeObj3 = new Shape (50,60);
a1.add(shapeObj1);
a1.add(shapeObj2);
a1.add(shapeObj3);
Comparator comp = new ComparatorExample().new ShapeComparator();
Collections.sort(a1, comp);
System.out.println(a1.toString());
}

}
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
First of all thanks to all (Stan James, Hentay Duke, Mark Spritzler, Kedar Dravid) who have given the valuable inputs,

Here I have tried for the solution of Comparator of the Shape class; as demonstrated in the PersonComparator Class

import java.util.*;

public class ComparatorExample
{

class ShapeComparator implements Comparator
{

public int compare(Object obj1, Object obj2)
{

return ((Shape)obj1).compareTo((Shape)obj2);
}
}


static ArrayList a1 = new ArrayList();

public static void main(String[] args)
{

Shape shapeObj1 = new Shape (10,20);
Shape shapeObj2 = new Shape (30,40);
Shape shapeObj3 = new Shape (50,60);
a1.add(shapeObj1);
a1.add(shapeObj2);
a1.add(shapeObj3);
Comparator comp = new ComparatorExample().new ShapeComparator();
Collections.sort(a1, comp);
System.out.println(a1.toString());
}

}
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
Moni, I'm not really interested in your actual name. I was just commenting on the fact that you were asked to comply with the naming conventions and didn't really change your name to something that did comply. But hey, I'll leave that to one of the Sheriffs. Are you still having troubles? If so, say so in your post. And use the code tags when posting code.
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
It is said that sometimes providing get methods in java program may break encapsulation, is it true then how to overcome this problem?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Don't provide any! Make objects do things, but not give you things. This is difficult or maybe impossible to do 100% of the time, but always a good goal to keep in mind. See if Knight's Principles or the Really Rather Good Idea of Demeter help figure it out.

That sounds like a new topic, and the kind of thing we talk about down in the OO, UML, etc. forum. Stroll (or scroll) on down and join us there for more.
[ July 29, 2005: Message edited by: Stan James ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
So does your above code compile? If not, what error messages do you get? How can we help you further.

Personally, there are seveal things with Kedar's example that I dislike. First, I think you should create the ShapeComparator class in it's own file so you don't have to worry about the messiness of inner classes yet. Second, the ShapeComparator assumes that Shape has a compareTo() method which means it probably implements the Comparable interface. If Shape impelements Comparable, there is no reason to have a separate ShapeComparator class. That's somewhat beside the point since you still need to figure out what it means to compare two Shape objects. So now you need to ask youself what it means for one Shape to be "less than", "greater than", or "equal to" another Shape. Based on your answer to this question, I suggest that you change the current compare() method to implement this definition.

If you need more help along these lines, please let us know.

Regards,

Layne


Java API Documentation
The Java Tutorial
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Thanks Layne,
Here is the complete code kindly go through it.
To define the shape class



To define the Comparator class
To define the Comparator classTo define the shape class
Hentay Duke
Ranch Hand

Joined: Oct 27, 2004
Posts: 198
How about telling us if the code is working the way you want or not and possibly any errors you might be getting, instead of "here's my code, go through it".

You said before you understood getters and setters and yet you have no getter for "y" and no setters at all. I haven't bothered to look at the other class, but I might if you put a bit more effort into the post (see first paragraph).

How's that changing your name to comply with the naming rules going? Mr M.
[ August 03, 2005: Message edited by: Hentay Duke ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

Moni M,

We take our naming convention rule rather seriously. People who repeatedly refuse to follow the rules of our community are asked to leave. I don't want to have to do that here. Please visit this page now, before posting any more, and add a full surname. Thank you.


[Jess in Action][AskingGoodQuestions]
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Moni Marva
Greenhorn

Joined: Jan 24, 2005
Posts: 23
Dear Ernest Friedman-Hill,

Actually I have replied to Hentay Duke on July 25, 2005 , regarding my surname and stated that " I am mostly identified by first name ", and further I have mentioned my surname as well . In India most of the places people will not add surname.
Nevertheless I have updated surname as desired by u.
Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333

First, I think you should create the ShapeComparator class in it's own file so you don't have to worry about the messiness of inner classes yet.

Well, inner classes have made it possible to code with less lines and in the process to obscure the code to the unenlightened, but make it wonderfully elegant to those who understand.
Moni Marwa should, of course, stay away from inner classes for the time being, and may be take a look at this (probably better) way of coding when she thinks she is comfy with inner classes.


Second, the ShapeComparator assumes that Shape has a compareTo() method which means it probably implements the Comparable interface. If Shape impelements Comparable, there is no reason to have a separate ShapeComparator class.

Yeah, that's right. At the time I made my previous post, I wasn't exactly trying to come out with the most elegant solution. BTW, here's how I'd probably do it if I were in no hurry:






Here's why there are 2 Comparator classes in the above code:
1) If I add another property to my bean class (Person), then I have to change the code in only my ComparatorExample class if I have to do the comparison based on the newly added properly.
2) If I have to change the property/field on which the Person(s) are to be compared, I just have to change the name of the class marked in bold above.
[ August 08, 2005: Message edited by: Kedar Dravid ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question On Comparator