Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

java - Can I use compareTo to sort integer and double values?

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?

Code:

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

For example:

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...