Java中的“int不能被解除引用”

我是Java的新手,我正在使用BlueJ。 我在尝试编译时不断得到“Int not be dereferenced”错误,我不确定问题是什么。 该错误特别发生在我底部的if语句中,其中“equals”是一个错误,“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(); } } } } 

id是基本类型int而不是Object 。 您不能像在这里那样调用基元上的方法:

 id.equals 

尝试替换这个:

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

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

基本上,你试图使用int就像它是一个Object ,它不是(嗯……它很复杂)

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

应该…

 id == list[pos].getItemNumber() 

假设getItemNumber()返回一个int ,替换

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

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

更改

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

 id == list[pos].getItemNumber() 

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

作为你的方法一个int数据类型,你应该使用“==”而不是equals()

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

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

它会修复错误。

尝试

 id == list[pos].getItemNumber() 

代替

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