[英]I am trying to make a method just like lastIndexOf() in class ArrayList but I am facing some issues finding the last index of an element
public int lastIndexOf(E o) {
int res = -1;
for(int i = 0; i < size() ; i++) {
if(o.equals(this.elementData[i]) ) {
return i;
}
}
return res;
}
}
我無法返回元素的最后一個索引。 假設我們有String tmp [] = {"EECS", "2030", "Class","Example about", "Array", "List", "Array", null, null, null};
在這里,我正在檢查tmp
中元素Array
的最后一個索引,但我的代碼返回元素出現的第一個索引。 我如何接近最后一個索引? 任何幫助,將不勝感激
您需要將return i
更改為res = i;
因為在找到第一個項目時,該方法將返回值並結束它,但您需要迭代到數組中的最后一個元素並在方法結束時返回該元素的索引:
public int lastIndexOf(E o) {
int res = -1;
for (int i = 0; i < size(); i++) {
if (o.equals(this.elementData[i])) {
res = i;
}
}
return res;
}
或者您可以嘗試從數組末尾檢查值的索引,如果找到元素,則在循環結束時返回索引,否則將返回res
,等於-1
表示未找到:
public int lastIndexOf(E o) {
int res = -1;
for (int i = (size() -1); i >= 0; i--) {
if (o.equals(this.elementData[i])) {
return i;
}
}
return res;
}
您應該從最后開始迭代,這樣當您找到 object 時,它肯定是最后一個,您不需要繼續遍歷數組的 rest。
public int lastIndexOf(E o) {
int res = -1;
for (int i = size() -1; i >= 0; i--)
{
if (o.equals(this.elementData[i]))
{
return i;
}
}
return res;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.