Java中的“int不能被取消引用”

Posted

技术标签:

【中文标题】Java中的“int不能被取消引用”【英文标题】:"int cannot be dereferenced" in Java 【发布时间】:2013-10-07 04:42:56 【问题描述】:

我对 Java 还很陌生,我正在使用 BlueJ。我在尝试编译时不断收到这个“Int cannot be dereferenced”错误,我不确定问题是什么。该错误特别发生在我底部的 if 语句中,它说“等于”是一个错误,“int 不能被取消引用”。希望得到一些帮助,因为我不知道该怎么做。提前谢谢!

public class Catalog 
    private Item[] list;
    private int size;

    // Construct an empty catalog with the specified capacity.
    public Catalog(int max) 
        list = new Item[max];
        size = 0;
    

    // Insert a new item into the catalog.
    // Throw a CatalogFull exception if the catalog is full.
    public void insert(Item obj) throws CatalogFull 
        if (list.length == size) 
            throw new CatalogFull();
        
        list[size] = obj;
        ++size;
    

    // Search the catalog for the item whose item number
    // is the parameter id.  Return the matching object 
    // if the search succeeds.  Throw an ItemNotFound
    // exception if the search fails.
    public Item find(int id) throws ItemNotFound 
        for (int pos = 0; pos < size; ++pos)
            if (id.equals(list[pos].getItemNumber())) //Getting error on "equals"
                return list[pos];
            
            else 
                throw new ItemNotFound();
            
        
    

【问题讨论】:

您正在尝试使用int,其中应该使用IntegerNumberObject...int 没有任何方法 【参考方案1】:

id 是基本类型 int 而不是 Object。您不能像在此处那样调用原语上的方法:

id.equals

尝试替换这个:

        if (id.equals(list[pos].getItemNumber())) //Getting error on "equals"

        if (id == list[pos].getItemNumber()) //Getting error on "equals"

【讨论】:

如果需要使用Integer.compareTo怎么办?【参考方案2】:

基本上,您尝试使用int,就好像它是Object,但事实并非如此(嗯...这很复杂)

id.equals(list[pos].getItemNumber())

应该是……

id == list[pos].getItemNumber()

【讨论】:

一个疑问:== 比较对象的引用和比较基元的值,对吧?如果我错了,请纠正。 是的。基元是特殊的。 实际学习界面时我收到了这个错误,谷歌搜索把我带到了这个答案。可以的话请看:error:int cannot be dereferencedSystem.out.println("A = " + A.AB);调用SOP的类实现了一个interface C,A是C的超接口。两个接口都定义了int AB。 A.AB 发生错误。 int AB 不能在任何interface 中声明,它只能在class 中声明...【参考方案3】:

假设getItemNumber()返回int,替换

if (id.equals(list[pos].getItemNumber()))

if (id == list[pos].getItemNumber())

【讨论】:

【参考方案4】:

改变

id.equals(list[pos].getItemNumber())

id == list[pos].getItemNumber()

有关详细信息,您应该了解基本类型(如 intchardouble)与引用类型之间的区别。

【讨论】:

【参考方案5】:

由于您的方法是 int 数据类型,您应该使用“==”而不是 equals()

尝试替换这个 if (id.equals(list[pos].getItemNumber()))

if (id.equals==list[pos].getItemNumber())

它将修复错误。

【讨论】:

【参考方案6】:

试试

id == list[pos].getItemNumber()

而不是

id.equals(list[pos].getItemNumber()

【讨论】:

以上是关于Java中的“int不能被取消引用”的主要内容,如果未能解决你的问题,请参考以下文章

Java中的ArrayList 重要方法补充

mySQL在java中的应用

关于JAVA 中的DOM操作

使用java 8中的forEach(..)而不是java 5中的forEach循环的任何优势[重复]

Java中的Math函数

java - 为啥在java中的poll方法之后PriorityQueue中的值会发生变化? [复制]