我不断从数据库中排序学生ID,经过很长时间搞清楚为什么它得到排序不正确,我的结论是这个比较与包装类的工作方式不同?Comparator与包装类有什么不同?
public class comparatorDemo {
public static void main(String[] args) {
Comparator<Integer> IDComparator = new Comparator<Integer>() {
@Override
public int compare(Integer firstID, Integer secondID) {
return firstID < secondID ? (-1) : (firstID == secondID ? (0) : (1));
}
};
System.out.println(IDComparator.compare(new Integer(1), new Integer(1))); // prints 1
System.out.println(IDComparator.compare((1),(1))); // prints 0
} }
这是怎么回事?
请使用经常使用的'Integer.valueOf()'获取缓存的Integer对象! – Unihedron
@Unihedron - 不需要。上面第二次调用“compare”的自动装箱功能可以解决这个问题。 –