I’ve got a list filled with ints:
List collection = new ArrayList();
collection.add(this.score1);
collection.add(this.score2);
collection.add(this.score3);
Now I want to compare the highest score with each individual score, to see which one(s) is the highest. Intuitively I tried to do it like so:
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";
}
However,
Collections.max(collection) == this.score1
Collections.max(collection) == this.score2
Collections.max(collection) == this.score3
all give me the error:
Incompatible operand types Comparable and int
However this seems to work:
int highestScoreValue = Collections.max(collection);
Now how can that be?
Why is Java allowing an int to be set to Collections.max(collection), however doesn’t allow an int to be compared with Collections.max(collection)?
Primitive types can’t be stored in Java collections, they automatically get boxed inside respective classes.
Whenever you do
list.add(score),scoreis first wrapped into anIntegerobject, then added to the collection.Now, when you call
Collections.maxan obect of type<T extends Object & Comparable<? super T>>is returned, and you are comparing it to a primitive type with==but this operator is only able to compare references to objects or directly primitive types and in your situation, since yourListparametric type is unspecified, the compiler is not able to unbox theIntegerinstance returned to anint.Possible solutions are to
Integer, thus allowing unboxingequalsmethod instead that==operator so that the score will be boxed to anIntegerand then compared to the result ofmax