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 / First Aid / March 2006

Tip: Looking for answers? Try searching our database.

sorting an ArrayList<Points> by x or y value

Thread view: 
emmoore - 17 Mar 2006 02:40 GMT
Hello everybody. I am rather new to Java, and I'm struggling understanding a
program I have to write that needs to use a Comparator. I really don't
understand how to use one or where to put it.

My task is to write a method sort(d) that will sort an ArrayList of points by
x value if d=0 and by y value if d=1. I think I've managed to create the
ArrayList of points needed, but I feel as if I've hit a complete impasse when
it comes to figuring out how to sort in the necessary way.

I've tried doing this a few different ways, all of which are wrong, but maybe
you might help steer me in the correct direction.

One try:

public static ArrayList<Point> sort(final int d)
 {
  Comparator MyLittlePointComparator = new Comparator()
{
  public int compare(Object o1, Object o2)
  {
    return compare( (Point)o1, (Point)o2);
  }
  public int compare(Point p, Point q)
  {
   int diff;
   
   if (d==0)
     diff = p.x - q.x;
   else if (d==1)
     diff = p.y - q.y;
   
   return diff;
  }
}
  return Collections.sort(this_use_array, MyLittlePointComparator());

Another try:
 public static ArrayList<Point> sort(final int d)
 {
   public class MyLittlePointComparator extends PS7File.EqComparator
implements Comparator<Point>
   {
     public int compare(Point p, Point q)
     {
   if (d == 0)
   {
     double pee = p.getX();
     double kyew = q.getX();
   }
   else if (d == 1)
   {
    double pee = p.getY();
    double kyew = q.getY();
   
   }
   if (pee < kyew) return -1;
   if (pee == kyew) return 0;
   return 1;
     }
   }
   return Collections.sort(this_use_array, new MyLittlePointComparator());
 }
}

I just have no idea where to even begin fixing this. The task seems so simple
(just sorting by x and y value), but I feel so lost. Thanks so much in
advance for your time and help.
Knute Johnson - 17 Mar 2006 03:19 GMT
> Hello everybody. I am rather new to Java, and I'm struggling understanding a
> program I have to write that needs to use a Comparator. I really don't
[quoted text clipped - 63 lines]
> (just sorting by x and y value), but I feel so lost. Thanks so much in
> advance for your time and help.

You need to read the docs on Comparator very closely.  The procedure in
a nutshell is to create a Comparator that will compare your Points by
the values.  Then all you have to do is call Collections.sort(yourList,
yourComparator).  Look at the Collections docs too.
Signature


Knute Johnson
email s/nospam/knute/

Roedy Green - 17 Mar 2006 03:32 GMT
>Hello everybody. I am rather new to Java, and I'm struggling understanding a
>program I have to write that needs to use a Comparator. I really don't
>understand how to use one or where to put it.

see http://mindprod.com/jgloss/comparator.html
http://mindprod.com/jgloss/sort.html
Signature

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

Patricia Shanahan - 17 Mar 2006 04:25 GMT
> Hello everybody. I am rather new to Java, and I'm struggling understanding a
> program I have to write that needs to use a Comparator. I really don't
[quoted text clipped - 4 lines]
> ArrayList of points needed, but I feel as if I've hit a complete impasse when
> it comes to figuring out how to sort in the necessary way.
...

I have a simplifying suggestion in addition to the comments posted by
Knute and Roedy.

Rather than trying to write a single Comparator that can do either job,
I would write two Comparator classes, one for each comparison rule, and
use the value of d to pick which Comparator to pass to sort.

Given this idea, you can make things easier for yourself by
concentrating on one side of the problem first and getting that to work.
Writing the second Comparator and the logic to choose between them
should be easy.

As well as implementing Comparable, Double has a static compare method
that compares two doubles and returns an int based on their order. It is
shorthand for:

new Double(d1).compareTo(new Double(d2))

Patricia
Roedy Green - 17 Mar 2006 04:52 GMT
>   public int compare(Point p, Point q)
>   {
[quoted text clipped - 7 lines]
>    return diff;
>   }

This piece of code reminds me a bit of a cartoon in Leo Brodie's
classic text "Thinking In Forth".  It shows a large machine, looking
something like an over-sized blender.

It has a metal plate saying "processor".  There is massive  toggle
switch you can switch to either "food" or "word".

You want two different but similar Comparators. Decide which algorithm
on to use at the head of the sort where you select which Comparator to
pass the sort,  not a zillion times in the innermost loop.
Signature

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

emmoore - 18 Mar 2006 20:17 GMT
Thank you everybody for your suggestions (I am VERY appreciative). I have
been reading through both the links, and I think they are helping. I also
took the suggestion of making two different comparators (here I attempted
just the one for X values). Perhaps I am still going about it the wrong way,
but I managed to get a piece of code that finally compiled.

import java.io.*;
import java.util.*;
import java.awt.*;

public class PointCollection2
{
 static ArrayList<Point> this_use_array;
 
 /*Using the method provided in the PS7File class to turn a file into an
ArrayList of points*/
 public static ArrayList<Point> PointCollection(File desired_file)
 {
   PS7File for_this_use = new PS7File(); //creates an object of type PS7File
so that the methods can be called in this class
   
   ArrayList<Point> this_use_array = for_this_use.points_from_file
(desired_file);
   
   return this_use_array; //the ArrayList of points needed for sorting is
created
 }
 
 public static ArrayList<Point> sort(int d)
 {
 Double pee, kyew;
 
 if (d == 0)
 {
   class MyLittlePointComparator extends PS7File.EqComparator implements
Comparator<Point>
  {
      public int compare(Point p, Point q)
      {
        Double pee = p.getX();
        Double kyew = q.getX();
        return (pee).compareTo(kyew);
      }
   }
   Collections.sort(this_use_array, new MyLittlePointComparator());
 }
 return this_use_array;
}
}

I write a tester program that also compiles.
import java.io.*;
import java.util.*;
import java.awt.*;

public class PointCollectionTest
{
 public static void main(String[] arg)
 {
   PointCollection2 tester = new PointCollection2();
   
   File tester_file = new File("C:\\Documents and Settings\\Elizabeth\\My
Documents\\Programming\\Programs\\randompoints.lst");
   
   ArrayList<Point> tester_array = tester.PointCollection(tester_file);
   
   ArrayList<Point> sorted_array = tester.sort(0);
   
   System.out.print(sorted_array);
 }
}

I'm not having much luck when I actually try to implement the program after
compiling.  I get a very nasty red error message in Dr. Java that reads:
NullPointerException:
 at java.util.Collections.sort(Unknown Source)
 at PointCollection2.sort(PointCollection2.java:34)
 at PointCollectionTest.main(PointCollectionTest.java:15)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)

I might have an idea what is wrong. I want to sort the arrayList (here,
this_use_array) made from the file of points with the method PointCollection.
I thought I fixed the problem by declaring this_use_array at the top before
writing any methods, but I guess that doesn't work?

I am not sure how to fix this.
Oliver Wong - 20 Mar 2006 23:16 GMT
> Thank you everybody for your suggestions (I am VERY appreciative). I have
> been reading through both the links, and I think they are helping. I also
[quoted text clipped - 90 lines]
>
> I am not sure how to fix this.

   Your sort(int) method reads from the static field this_use_array,
however you never actually initialize that field, and so it has a default
value of null. You seem to have a factory method called
PointCollection(File). It declares a local variable called this_use_array
which is initializes. Probably you meant to initialize the static field
rather than this local variable.

   - Oliver


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.