compareTo()实现问题 [英] compareTo() implementation problems

查看:350
本文介绍了compareTo()实现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实现compareTo方法时遇到了麻烦。我找到了答案但没有任何帮助。我正在尝试用各种大小的圆填充TreeSet。我需要在我的圈子类中进行compareTo才能以这种方式存储它们。

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;
    }
}
}

编辑:谢谢我忘记了一些东西:
Circle不是抽象的并且不会覆盖比较中的抽象方法compareTo(Object)

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)


推荐答案

在此方法中永远不会返回-1。如果其中一个圆圈与另一个圆圈相比更大,则该圆圈应该返回1,而另一个圆圈与更大的圆圈相比应该返回-1。你必须确保你的圆圈遵循传递属性和其他一些guildelines。

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.

看看这个对compareTo()的引用。

这篇关于compareTo()实现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆