Java:比较ints之谜
我有一个充满INT的列表:Java:比较ints之谜,java,int,Java,Int,我有一个充满INT的列表: List collection = new ArrayList(); collection.add(this.score1); collection.add(this.score2); collection.add(this.score3); 现在我想将最高分数与每个分数进行比较,看看哪一个分数最高。直觉上,我试着这样做: String highestScore; if(Collections.max(collection) == this.score1) { h
List collection = new ArrayList();
collection.add(this.score1);
collection.add(this.score2);
collection.add(this.score3);
现在我想将最高分数与每个分数进行比较,看看哪一个分数最高。直觉上,我试着这样做:
String highestScore;
if(Collections.max(collection) == this.score1) {
highestScore = "Score 1";
}
if(Collections.max(collection) == this.score2) {
highestScore += ", Score 2";
}
if(Collections.max(collection) == this.score3) {
highestScore += ", Score 3";
}
但是,
Collections.max(collection) == this.score1
Collections.max(collection) == this.score2
Collections.max(collection) == this.score3
请告诉我错误:
与int和compariable不兼容的操作数类型
然而,这似乎是可行的:
int highestScoreValue = Collections.max(collection);
那怎么可能呢
为什么Java允许将int设置为Collections.max(collection)
,但不允许将int与Collections.max(collection)
进行比较?尝试使用equals()
进行比较:
Collections.max(collection).equals(this.score1)
请注意,该方法返回一个
可比较的
对象,该对象不能与=
和int
进行比较。另一个选项是首先将其强制转换为整数
。作为旁注,这不是找到最大值的最有效方法,您在原语类型和对象类型之间来回切换。最好为整数实现自己的max
方法。原语类型不能存储在Java集合中,它们会自动装入相应的类中
无论何时执行list.add(score)
,score
首先被包装到Integer
对象中,然后添加到集合中
现在,当您调用
Collections.max
类型为List collection=new ArrayList()的对象时代码>可能会起作用。如前所述,您的列表是一个列表
…看起来像int highestScoreValue=Collections.max(collection)代码>编译器可以使用LHS上的声明推断返回类型。因此,在这种情况下,max方法返回一个整数
(然后自动取消装箱),而不是可比
。不要使用原始类型。接受assylias的建议并声明集合的参数化类型。