Java: comparison of mystery ints

I have 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 against each individual score to see which one is the highest. Intuitively, I tried to do it like this:

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

      

everyone gives me an error:

Incompatible operand types Comparable and int

However, this seems to work:

int highestScoreValue =  Collections.max(collection);

      

Now how can this be?

Why is Java allowing int to be set Collections.max(collection)

but not allowing int to be compared Collections.max(collection)

?

+3


source to share


2 answers


Primitive types cannot be stored in Java collections, they automatically fall into the appropriate classes.

Whenever you execute list.add(score)

, it is score

first put into an object Integer

and then added to the collection.

Now when you call Collections.max

, an object of the type is returned <T extends Object & Comparable<? super T>>

and you are comparing it to the primitive type with ==

, but this operator can only compare object references or directly primitive types and in your situation, since your parametric type is List

not specified, the compiler cannot unpack the instance Integer

returned to int

.



Possible solutions:

  • returns the return value in Integer

    , which allows unpacking
  • use the equals

    method instead so ==

    that the score is placed in a cell Integer

    and then compared to the resultmax

+5


source


Try to use equals()

for comparison:

Collections.max(collection).equals(this.score1)

      



Note that the method max()

returns an object Comparable

that cannot be matched ==

against int

. Another option is to translate it to first Integer

. As a side note, this is not the most efficient way to find the maximum value, you switch between primitive types and object types. Better to implement your own method max

for integers.

+2


source







All Articles