Thread: Java Sorting Array of points!

1. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0

Java Sorting Array of points!

Haha as i promised, i need help again! (: well, sorting help now, my current code, adds points to an array, then finds the total and average, now i would like to sort the arraylist, by acceding order of X's stored in the points, within the arraylist.

The code:
Java Code:
```package medianmedianline;
import java.util.*;
import java.awt.*;;
public class Main {
public static void main(String[] args) {
int size;
double x2 = 0;
double y2 = 0;
int count1 = 0;
int count2 = 0;
int x1 = 0;
int y1 = 0;

ArrayList <Point> point = new ArrayList();

while(count1 < 10){
x1 = count1;
y1 = count1;
count1++;
}

while(count2 < point.size()){
x2 = x2 + point.get(count2).getX();
y2 = y2 + point.get(count2).getY();
count2++;
}

System.out.println("X: " + x2);
System.out.println("Y: " + y2);
System.out.println();
System.out.println("Average X: " + (x2/point.size()));
System.out.println("Average Y: " + (y2/point.size()));
}
}```
Unfortunately, its not as simple as Collections.sort(list1); ):

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14

You might want to mark that one as finished, or having evolved to higher things or whatever. And leave a link pointing to this one.

3. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
Yea, i read it, and this is what i wrote:

Yea, my research has told me this, I notices that there is natural order, and another type of ordering. is natural order, order only based on like variables? Allso, i need equal elements to be sorted in my case.

I need lots of heal haha. With on last bump, i can finish the written version. then begins the work of the the gui version XD but im good with gui.

4. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
HELPPPPPP! haha.

5. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
i can finish the written version. then begins the work of the the gui version

What? You implement the behaviour then you write the gui? There's an attitude that deserves to be encouraged!

Java Code:
```// Person.java

import java.util.Comparator;

public class Person {

private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public static final Comparator<Person> NAME_COMP = new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.name.compareTo(o2.name);
}
};

public static final Comparator<Person> AGE_COMP = new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.age - o2.age;
}
};

public String getName() {return name;}
public int getAge() {return age;}

@Override
public String toString() {
return String.format("%s - %d", name, age);
}
}

// PersonDriver.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PersonDriver {
public static void main(String[] args) {
List<Person> data = new ArrayList<Person>();

System.out.printf("    raw: %s%n", data);
Collections.sort(data, Person.AGE_COMP);
System.out.printf(" by age: %s%n", data);
Collections.sort(data, Person.NAME_COMP);
System.out.printf("by name: %s%n", data);

// a comparator to sort by age.  but in the event of equal ages the sort
// will be performed by name
Comparator<Person> ageNameComp = new Comparator<Person>() {
public int compare(Person o1, Person o2) {
int ret = o2.getAge() - o1.getAge();
if(ret != 0) {
return ret;
}
return o1.getName().compareTo(o2.getName());
}
};
Collections.sort(data, ageNameComp);
System.out.printf("by both: %s%n", data);

}
}```

People, like shoes and points, can be sorted in lots of different ways. In the example I imagine that Person.java was written by someone else. They have provided a couple of comparators which I use.

But the driver class also creates its own comparator, based on the public accessor methods of Person, to sort by age and, in the case of two people of the same age it provides a specific ordering based on name.

There are complexities which I've ignored (the possibility of subclassing Person, people with the same name and age etc) but you might obtain some idea for this that will be useful for writing your own code with Point.
Last edited by pbrockway2; 10-27-2010 at 01:24 AM. Reason: wrong code

6. I second pbrockway's recommendation: create a small utility class, a Comparator<Point> class and use that to sort your points. This class will only have one method, compare(Point p1, Point p2), and in this method you will return 1 if p1 > p2 (however you decide this), -1 if p1 < p2, and 0 if p1 equals p2. Then it's as simple as calling Collections.sort(myList, new MyComparator()), and your done!

edit: this was posted before I saw pbrockway's detailed post above. I say go with whatever he says. :)

7. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
What? You implement the behaviour then you write the gui? There's an attitude that deserves to be encouraged!
Haha whatt? haha, ok, to my new question.

The comparator confuses me, mainly because i just need something simple to learn from. haha i learn best from examples. That aside, i was wondering how i call comparator, would i have to just simple implement it somewhere in my main class, or would i need to make a new object class for it, and then kinda re-write my code around it? (Im sure i just made that sound completely different then i mean it). Anyways, im not sure why, but i use lots of object when i use gui, but when im concept writing my programs i seam to keep it sequenced haha. i dont know why though. By the way, this is not the first program ive writen for this idea, ive writen like 4 others for other sections of the over all concept, and with the completion of this i will be able to complete a beta version!

8. Originally Posted by Jcbconway
Haha whatt? haha, ok, to my new question.

The comparator confuses me, mainly because i just need something simple to learn from. haha i learn best from examples.
um.... I thought pbrockway's post above actually has good examples. Have a look at them.

That aside, i was wondering how i call comparator, would i have to just simple implement it somewhere in my main class, or would i need to make a new object class for it, and then kinda re-write my code around it? (Im sure i just made that sound completely different then i mean it).
Again, pbrockway's post shows this too. Have you looked at it?

9. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
Well i looked at it, but it confuses me. because it has extras. you see it as easy because you focus is not complete on comparator, and its easy for you to understand haah (: im compiling it and messing with it as we speak, but im slow sometimes haha.

10. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
In my return statement, it says it needs an int, but i have to use a double for the point? Here is what i have:

Java Code:
```Comparator<Point> pointorder = new Comparator<Point>(){
public int compare(Point o1, Point o2) {
double sort = o2.getX() - o1.getX();
if(sort != 0) {
return sort;
}
}
};```
I get an error at return sort; but, if i make sort an int, i get an invalid compare type with the points XD lol, classic catch 22.

11. if a method says it is going to return an int, it must return an int in all situations. In your code above, if o1's x == o2's x, then your method returns nothing when it should return 0.

12. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
So this?

Java Code:
```Comparator<Point> pointorder = new Comparator<Point>(){
public int compare(Point o1, Point o2) {
[COLOR="Red"]double sort = o2.getX() - o1.getX();[/COLOR]
if(sort != 0) {
[COLOR="Red"] return sort;[/COLOR]
}
return 0;
}
};```
Haha, it would return 0 if the if returns false, but, im still stuck the red lines are the parts that have me stuck. The first one, i have to say double sort, because double sort is determined by my point, which needs a double right? and the return statement when the if is true, requires an int type value, not a double.

13. A method most return the type that it has declared it will return, and the compare method is no exception. As you can see, the method signature is not ambiguous -- it returns an int:

Java Code:
`public [color="red"]int[/color] compare(Point o1, Point o2) {`
So the body of your code absolutely must abide by this contract -- there's no getting around it. So return an int, not a double. By the way, what does the API for Point say that its x and y fields hold, int or double?

14. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
Im not sure haha, its just, the top red line is the error when its an int, and the return is find, i change it to a double, and the top line is fine, but the return is an error. Haha,

15. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
"A point representing a location in (x,y) coordinate space, specified in integer precision." thats what it says, but i only get more confused as to how i use this whole thing haha.

16. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
But in the getX(); meathod, it returns the X cordinate in double. so, idk haha.

17. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
I think we might be confused about the meaning of what the compare() returns.

It always returns an int - and that has nothing to do with using a double for the coordinate location. If you look at the example the name comparator also returns an int (even though the names are strings). Basically the compare() method returns a negative number when a little thing is compared to a big thing, a positive number when a big thing is compared to a little thing and zero when equal things are compared.

If you are comparing double values then subtract them and then just return an int value that depends on the sign of the difference.

18. Senior Member
Join Date
Sep 2010
Posts
109
Rep Power
0
Yea, but how do i return the value of sort weather it be +, or - ? Sort is a double, so i cannot return sort, and if i cant return sort, what am i suppose to return? haha, im missing something here (:

19. Originally Posted by Jcbconway
But in the getX(); meathod, it returns the X cordinate in double. so, idk haha.
So it does... my bad. Myself, with the Point class, I've always just accessed the fields directly via o1.x and o2.x.

20. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
But in the getX(); meathod, it returns the X cordinate in double. so, idk haha

In fact you have a choice the get?() methods return double. But the fields themselves (x and y) are public and they're ints.

You might as well use the int fields as that will save you forcing the result of the subtraction to be an int.

Page 1 of 2 12 Last

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•