compareTo Error: Cannot invoke compareTo(int) on the primitive type int

前端 未结 2 1751
广开言路
广开言路 2021-01-27 01:56

Not sure how to get the compareTo to not give error.

Very lost. Tried changing multiples lines of code.

public voide addValue(int newNumber)         


        
相关标签:
2条回答
  • 2021-01-27 02:37

    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.
    
    0 讨论(0)
  • 2021-01-27 02:43

    "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.

    0 讨论(0)
提交回复
热议问题