Lets say I have a class
public class Data{
public int k;
public int l;
public Data(int k, int l){
this.k = k;
this.l = l;
}
public boolean equals(Date m){
if(this.k == m.k && this.l = m.l)
return true;
return false;
}
}
And I add a few Data objects to a ArrayList:
ArrayList<Data> holder = new ArrayList<Data>;
Data one = new Data(0,0);
Data two = new Data(0,4);
Data three = new Data(0,5);
Why does indexOf not find this?:
holder.indexOf(new Data(0,4)); //returns -1
Is indexOf any better than going through the whole array list myself? Or am I missing something.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
int indexOf(Object o) indexOf(Object o) method is used to search for a specified element in ArrayList and return its index. If it doesn't find the element, then it returns -1. indexOf() method searches element from the 0th index to ArrayList's size.
The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.
The indexOf()
method does go through the entire list. Here's an excerpt from Java 7 source code:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
It'd be better to let Java go through it than write it yourself. Just make sure that your equals
method is sufficient at finding the object you want. You'll also want to override hashCode()
as well.
I won't write your equals
method out, but I would recommend that you at least:
if(boolean_expr) { return true; }
; just return the boolean expression.equals
method - the signature of that requires an Object
parameter, not Date
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With