CompareTo功能问题

时间:2015-04-09 05:58:42

标签: java compareto

帮助我无法找出compareTo函数。这就是我要做的:编写一个compareTo函数,可以用来按顺序放置产品 他们的部分号码。也就是说,后来按字母顺序排列的部件号 order大于按字母顺序排列的零件号。 这是我的代码:

public class ProductType implements Comparable<ProductType> {
    private String partnum;
    private double price;
    private int stock;

    public ProductType(String partnum, double price, int stock) {
        this.partnum = partnum;
        this.price = price;
        this.stock = stock;
    }

    public ProductType() {
        partnum = "";
        price = 0;
        stock = 0;
    }

    public void setNum(String partnum) {
        this.partnum = partnum;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public String getNum() {
        return partnum;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public int compareTo(ProductType otherType) throws NullPointerExeption {
        if (otherType == null)
            throw new NullPointerException();
        return (this.getNum().compareTo.otherType.getNum());
    }

    public String toString() {
        String result = "" + this.getNum();
        return result;
    }
}

1 个答案:

答案 0 :(得分:4)

更改您的退货声明

 return (this.getNum().compareTo.otherType.getNum());

 return (this.getNum().compareTo(otherType.getNum()));

因为compareTo()是方法。

在调用compareTo()方法之前检查是否

null != this.getNum()

否则你会获得NPE。