. Advertisement .
..3..
. Advertisement .
..4..
I am working on java, but I found the following warning message:
Error Message: "Cannot invoke compareTo(int) on the primitive type
int"
Is there any way to stabilize the issue “cannot invoke compareto(int) on the primitive type int”?
I read a lot of topics about this, but all of them were trying to install anything. Is this the correct way, or any recommendation for me?
Please find the beginning command below:
public voide addValue(int newNumber){
int index = 0;
while ((index < numbers.size()) && (numbers.get(index.compareTo(newNumber) ==-1))
index++;
numbers.add(index, NewNumber);
}
The cause: In my opinion, the primitive type
int
isn’t a reference type likeInteger
, Primitive values cannot be used to call methods. You may easily compare two ints by typingindex newNumber
.Solution: Because primitive types are not Java objects, they lack methods. Use the matching class, please:
It is important to realize that the primitive
int
typeint
, unlikeInteger
, is not a reference type. methods cannot be called on primitive values. If you need to compare two ints you can useindex < newNumber
as an example.Alternativly, you can use the static method comparison of Integer classes, such as
Integer.compare(index, newValue)
. You don’t have to use methods to compare primitive value, you can do it “in place”.Notice: In other languages like Kotlin there is no such distinction. You can only have Int objects and call methods on them. Java makes this distinction. Study it and you’ll learn which approach to use.