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

11,114

Solution 1

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

Solution 2

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.
Share:
11,114

Related videos on Youtube

Lil D
Author by

Lil D

Updated on June 04, 2022

Comments

  • Lil D
    Lil D almost 2 years

    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"