Comparator - int无法解除引用 [英] Comparator - int cannot be dereferenced

查看:138
本文介绍了Comparator - int无法解除引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这里看到一个例子,如何使用Comparator接口对ArrayList进行排序,所以我试了一下。使用Strings它完美地工作,但是我想要将一个变量排序为Integer,它将无法编译,说int无法解除引用。

So I saw an example on here how to sort an ArrayList using the Comparator interface, so I tried it out. With Strings it worked perfectly, but with one variable that I want to sort being an Integer, it will not compile, saying "int cannot be dereferenced".

我能做什么?这样做,这将允许我按分数变量对ArrayList进行排序?

What can I do so that this will work and allow me to sort an ArrayList by the score variable?

这是我的代码:

public class ScoreComparator implements Comparator<Review> {

@Override
public int compare(Review o1, Review o2)
{
   return o1.getScore().compareTo(o2.getScore());
}
}

感谢您的帮助!

推荐答案

你不能在 int s上调用方法;没有 compareTo 方法来调用。这将是盒装的整数类型,但拳击会有点过分。

You can't call methods on ints; there's no compareTo method to call. That would be on the boxed Integer type, but boxing would be overkill.

如果您使用的是Java 7 +,你应该写

If you're on Java 7+, you should write

return Integer.compare(o1.getScore(), o2.getScore());

...否则你或多或少需要写

...otherwise you'll more or less need to write

if (o1.getScore() < o2.getScore()) {
   return -1;
} else if (o1.getScore() > o2.getScore()) {
   return 1;
} else {
   return 0;
}

这篇关于Comparator - int无法解除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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