Java: a neat mysterious veil

I have a list of filled integers:

List collection = new ArrayList();
collection.add(this.score1);
collection.add(this.score2);
collection.add(this.score3);

Now I want to compare the highest score of each individual score to see which score is the highest Intuitively, I tried to do 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

Give me mistakes:

However, this seems to work:

int highestscoreValue =  Collections.max(collection);

How about now?

Why does Java allow int to be set to collections Max (Collection), but int and collections are not allowed Max (set) for comparison?

Solution

Primitive types cannot be stored in Java collections. They are automatically wrapped in the corresponding classes

Whenever you execute a list When add (score), the score is first wrapped in an integer object and then added to the collection

Now, when you call collections Max, objects of type < T extends object & Comparable & lt;? Super T > > returns, and you compare it with the basic type with = =, but this operator can only compare the reference of the object or the direct original type and your situation. Because the list parameter type is not specified, the compiler cannot unbox the integer instance and return int

The possible solution is

>Cast the return value to integer, allowing unboxing > use the equals method instead of the = = operator to box fractions into integers and then compare them to the maximum result

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>