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

纵饮孤独 提交于 2021-02-05 07:57:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!