This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I wrote a simple program which reads in a list of points from a text file and arranges them into an ArrayList. I wrote a method which calculates the absolute distances (cab distance) of each point (absolute value of the x value plus the absolute value of the y value). I also wrote another method which prints the x and y value of the points in the ArrayList along with the cab distance of the points. What I want to do now is write a method that will accept the ArrayList with the points and sort the points once again by their cab distance. It will be much like the first method, but the points will be sorted when they are printed. Any ideas? My code is attached. Thanks!
Surely the cabDistance() method should be an instance method of the point class? And the x and y fields should have private access. Initialise them via the constructor, and don’t use (0, 0) as a default.
I presume you are familiar with the appropriate Java Tutorials Section. That has a part about ordering, which will help you. Simply, you need to decide that points have a natural ordering (which they probably haven’t) and you can implement the Comparable interface, or you can decide that some feature allows you to apply an ordering, maybe the cab distance, and you can create a Comparator object which orders your points by cab distance. In which case points (4, 5), (5, 4) and (6, 3) will count as equivalent to one another.
Joined: Nov 29, 2012
I was thinking about trying to use some type of insertion sorting or a selection sort. In other words, I want to refrain from using Comparator. I want to keep the method void and only pass in an ArrayList. I know that points have natural ordering, however, the cabDistance of each is an absolute distance. This differs with their natural distance. Would i be able to create a new arrayList and sort the points back into there and then print that list?