我可以使用compareTo对整数和双精度值进行排序吗? [英] Can I use compareTo to sort integer and double values?

查看:127
本文介绍了我可以使用compareTo对整数和双精度值进行排序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用compareTo对整数和双精度值进行排序吗?我的系统给了我一个错误,我不能在原始类型int上调用compareTo(int)。任何想法?

Can I use compareTo to sort integer and double values? My system gives me an error that I Cannot invoke compareTo(int) on the primitive type int. any ideas?

代码:

public int compare(Object o1, Object o2) {  
Record o1C = (Record)o1;
Record o2C = (Record)o2;                
return o1C.getPrice().compareTo(o2C.getPrice());
}

class Record
    public class Record {
    String name;
    int price;    

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
}


推荐答案

好,编译器的权利:)你不能直接调用 compareTo 。但是,根据您使用的Java版本,您可以使用 Integer.compare (1.7中介绍)和 Double.compare (在1.4中引入)。

Well, the compiler's right :) You can't call compareTo directly. However, depending on the version of Java you're using, you can use Integer.compare (introduced in 1.7) and Double.compare (introduced in 1.4).

例如:

return Integer.compare(o1C.getPrice(), o2C.getPrice());

如果您不在1.7并且仍想使用内置方法,那么可以使用:

If you're not on 1.7 and still want to use built-in methods, you could use:

Integer price1 = o1C.getPrice();
Integer price2 = o2C.getPrice();
return price1.compareTo(price2);

...但这将使用不必要的装箱。鉴于对大型集合进行排序可以进行相当多的比较,这并不理想。在您准备使用1.7之前,可能值得重写比较。这很简单:

... but this will use unnecessary boxing. Given that sorting a large collection can perform really quite a lot of comparisons, that's not ideal. It may be worth rewriting compare yourself, until you're ready to use 1.7. It's dead simple:

public static int compare(int x, int y) {
    return x < y ? -1
         : x > y ? 1
         : 0;
}

这篇关于我可以使用compareTo对整数和双精度值进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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