问题
Not sure how to get the compareTo
to not give error.
Very lost. Tried changing multiples lines of code.
public voide addValue(int newNumber){
int index = 0;
while ((index < numbers.size()) && (numbers.get(index.compareTo(newNumber) ==-1))
index++;
numbers.add(index, NewNumber);
}
I expected it to be able to have no issues with compareTo(newNumber)
.
Error Message: "Cannot invoke
compareTo(int)
on the primitive type int"
回答1:
Edit: I can't believe what I originally wrote here.
Can you not just use a relational comparison operator here?
(firstNum < secondNum) // This will return a boolean value of true or false.
回答2:
"Cannot invoke compareTo(int) on the primitive type int"
You have to understand: the primitive type int
isn't a reference type like Integer
. You can't call methods on primitive values. When you want to compare two ints, you can simply do index < newNumber
for example.
Alternatively, you could use that static method compare of the Integer class, like: Integer.compare(index, newValue)
. But as said: you don't need methods to compare primitive values, you can directly do that "in place".
Note: in other languages, like Kotlin, there is no such difference. There you only have Int objects, and call methods on those. But java makes that distinction. So study it, and learn how to use which approach.
来源:https://stackoverflow.com/questions/57836294/compareto-error-cannot-invoke-comparetoint-on-the-primitive-type-int