Reputation:
int found = 0;
int index = 0;
while (index < list.size()) {
if(list.get(index) == z) {
found = index;
}
index++;
}
return found;
z is just the name of the object I am trying to figure out why this is wrong for finding the lastIndexOf in an arraylist without using the lastIndexOf method that's already build into java.
could someone point my in the right direction as to what I am doing wrong?
Upvotes: 1
Views: 486
Reputation: 234695
Three issues:
1) You ought to return an index that is not a valid index of the container if an element is not found. Let's use -1, although the Java bods might do a better job than this such as returning a negative value related to where an element would be if it were in the container.
2) You need to start from the end of the list and work backwards. Else you will not necessarily find the last one.
3) Don't use ==
to compare values. Use equals
instead.
Putting this together, having removed a redundant variable, gives you
int index;
for (index = list == null ? -1 : list.size() - 1; index >= 0; --index){
if (list.get(index).equals(z)){
break;
}
}
return index;
There are probably better ways of traversing the container: I've unwittingly built an O(N * N) algorithm for containers where random lookup is O(N), but this ought to get you started.
Upvotes: 2
Reputation: 393811
First of all, you want to use equals
and not compare references with ==
.
Second of all, you want the initial value of found
to be -1
, in case you don't find the element in the list (since otherwise you'll return 0
, which is a valid index, when the element is not found).
int found=-1;
int index=0;
while (index<list.size()){
if(list.get(index).equals(z)){
found=index;
}
index++;
}
return found;
Of course it would be more efficient to iterate from the end of the list backwards.
int index=list.size() - 1;
while (index >= 0){
if(list.get(index).equals(z)){
return index;
}
index--;
}
return -1;
Upvotes: 2