21227

compareTo() implementation problems

Question:

Hi i'm having trouble implementing the compareTo method. I've looked for answers but nothing has been any help. I'm trying to fill a TreeSet with various sizes of circles. I need compareTo in my circle class to be able to store them this way.

import java.util.*; import java.lang.*; abstract class Shape { private String name; //e.g."circlel", "rectangle3" Shape(String name0) { name = name0; } abstract double area (); // area of shape abstract double perim(); // length of perimeter of shape void put() { // display shape details System.out.println(name + " with area " + area() + " and perimeter " + perim() ); } } class Circle extends Shape implements Comparable { private static String name; private int radius; Circle(String n, int r) { super(n); radius = r; } public double area() { return Math.PI * radius * radius; } public double perim() { return 2 * Math.PI * radius; } public int compareTo(Circle c) { if(c.name == name && c.radius == radius) { return 0; } else { return 1; } } }

Edit: Thanks I was forgetting something: Circle is not abstract and does not overide abstract method compareTo(Object) in Comparable

Thanks for the help on that, now that I have gotten down to testing the class, when try to add a circle to the treeset this exception pops up any ideas,

Exception in thread "main" java.lang.NullPointerException at Circle.compareTo(Shape.java:47) at Circle.compareTo(Shape.java:23) at java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at CircleTreeSet.main(CircleTreeSet.java:24)

Answer1:

You are never returning -1 in this method. If one of the circles is "greater" in comparision to the other, that one should return 1 and the other one, if compared to the greater one, should return -1. You must make sure that your circle follows transitive properties and some other guildelines.

Take a look at <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29" rel="nofollow">this reference to the compareTo()</a>.

Answer2:

You must return -1 if the current instance is less than c, 1 if the current instance is greater than c, and 0 if the instances are equal.

That's how compareTo works. Right now it you're treating it more like an equality check. comparTo does more than that. It should determine if an item is equal, less than, or greater than another item.

This code will group objects with the same name in order of size when sorted. Objects also will be sorted alphabetically by name.

public int compareTo(Circle c) { if(c.name.equals(name)){ if(c.radius < radius) { return 1; } else if(c.radius>radius) { return -1; } return 0; } //names aren't the same compare alphabetically. return this.name.compareTo(c.name); }

Recommend

  • angularjs ng-bind-html html input part missing
  • How do I properly code a javascript property and method using the 'prototype' function?
  • Circle movement upon rectangle Collision
  • SSRS 2008 - Sorting within a group
  • How to change placeholder text in an autocomplete activity of android google place?
  • Where these are stored?
  • Reading a file into a multidimensional array
  • AndEngine Applying Transparancy to AndEngine View
  • Using a canvas object in a thread to do simple animations - Java
  • App restarts from wrong activity
  • Jetty Server not starting: Unable to establish loopback connection
  • Java: can you cast Class into a specific interface?
  • Projection media query: browser support and workarounds?
  • Master page gives error
  • JFileChooser in front of fullscreen Swing application
  • HTML download movie download link
  • How to draw moving and Running sine wave chart using JFree chart in java?
  • AES padding and writing the ciphertext to a disk file
  • Possible to stop flickering java tooltip in heavyweight mode?
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Updating server-side rendering client-side
  • How to extract text from Word files using C#?
  • sending/ receiving email in Java
  • Eraser for UIBezierPath
  • ActionScript 2 vs ActionScript 3 performance
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • To display the title for the current loaction in map in iphone
  • Traverse Array and Display in markup
  • Matrix multiplication with MKL
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • Suggestions to manage Login/Logout transitions
  • How to set the response of a form post action to a iframe source?
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • How does Linux kernel interrupt the application?
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?