Loop over your array to find the position of your object, using whatever equality check you require.
EDIT:
As everyone seems to be concerned over .equals
vs ==
I've changed the routine to perform either. If you're checking for reference equality, use findValue(ary, obj, true)
, otherwise use findValue(ary, obj, false)
This will not find null values. I suggest throwing an exception here if myObject
is null, but I will leave that decision to you.
public int findValue(Object[] objects, Object myObject, boolean equalityCheck){
for(int i=0;i<objects.length;i++){
if(equalityCheck){
if(objects[i] == myObject){
return i;
}
}else{
if(objects[i]!=null && myObject!=null && objects[i].equals(myObject)){
return i;
}
}
}
return -1;
}
This code is performing a linear search to find the position of the object. Its not very efficient on larger arrays. As you seem to be a beginner I'm not going to dive into how to optimize this, but just be aware.