我正在尝试创建一个方法removeAnObject
,它从数组中删除一个对象并返回一个布尔值,但是当我尝试使用该方法时,我遇到了一个奇怪的symbol not found
错误从Arraylist类中删除方法。
这是方法:
public boolean removeAnObject(Element anObject)
{
int whereWeAre;
String paramClass;
String currClass;
boolean weFoundIt;
paramClass = anObject.getClassName();
whereWeAre = 0;
weFoundIt = false;
while(whereWeAre != currentSize && weFoundIt == false)
{
currClass = theList[whereWeAre].getClassName();
if(currClass.equals(paramClass))
{
theList.remove(whereWeAre);
weFoundIt = true;
}
else
{
whereWeAre++;
}
}
return weFoundIt;
}
这是错误:
ElementSet.java:262: error: cannot find symbol
theList.remove(theList[whereWeAre]);
^
symbol: method remove(Element)
location: variable theList of type Element[]
1 error
最后说明:我在课程开头有import java.util.ArrayList
。
答案 0 :(得分:0)
使用int作为ArrayList参数的remove(parameter)方法也有一个E类型的返回值,它是创建列表时指定的Object类型Object。
所以对于初学者来说,当你使用List []我假设它是一个ArrayLists数组() 并且您确定该List的类型为ArrayList而不是Array。
1-保存并重新编译代码,错误行在您指定的代码中无处可用 2-如果您使用上面指定的方法,请确保列表[whereWeAre]为int。
3-为什么不直接使用ArrayList()类中包含的方法:
public boolean remove(Object o)
将删除对象的第一个出现,如果成功则返回true。 点击此处了解详情:Docs
答案 1 :(得分:-1)
如果使用数组,则替换:
theList.remove(whereWeAre);
与
theList[whereWeAre] = null;
此行会使地点whereWeAre
为空,从而移除搜索到的Element
。
如果您打算在同一个数组上多次重用您的方法,请不要忘记添加空检查条件。否则,您将面临NullPointerException
。
while(whereWeAre != currentSize && weFoundIt == false)
{
if (theList[whereWeAre]!=null)
{
currClass = theList[whereWeAre].getClassName();
if(currClass.equals(paramClass))
{
theList.remove(whereWeAre);
weFoundIt = true;
}
else
{
whereWeAre++;
}
}
else
{
whereWeAre++;
}
}