Reputation: 752
I have created a model
public class Portfolio {
private String id;
private String name;
public Portfolio() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
i have a list of this model. i want to find a position of an specific item in it.
I have tried
Portfolio p = new Portfolio();
p.setId("1");
p.setName("Test");
int i = PortfolioList.indexOf(p);
when i log the value of "i" it returns "-1". but i m sure the "p" object is available in arraylist.
i dont want to use for() loop. i think it takes time to find an object, if there is so many objects in our arraylist.
what is the currect way of using indexOf() method?
Upvotes: 2
Views: 1426
Reputation: 2815
In this case you are try to avoid for loop right? So better you can use hashmap..
Refer here : https://developer.android.com/reference/java/util/HashMap.html
Upvotes: 1
Reputation: 461
The problem is that your class Portfolio
does not override the equals()
method from java.lang.Object. Therefore, when indexOf()
is searching for an element, it will just use the implementation of equals()
from Object, which simply does a check if the two objects are actually the same instance. You can see more about that on the following resource:
https://javaranch.com/journal/2002/10/equalhash.html
Given that you just created the object p
in your code snippet, it will not be the same instance that was stored in the ArrayList, therefore it will always return not found.
The way to fix this would be to create your own implementation of equals()
in your Portfolio
class. However, there is no need for you to do that tedious job yourself. Instead, I highly recommend that you use the AutoValue annotation:
https://github.com/google/auto/blob/master/value/userguide/index.md
AutoValue will actually reduce your current Portfolio
class, and make the equals()
and hashCode()
for you for free. Take a look at the above link and this can help you a bunch.
Upvotes: 1
Reputation: 6616
Surely the p
object is not present in the list. Running indexOf
on the list will try to find the object based on reference. So if the reference is not present you will not find the object.
Why do you want to avoid the for
loop? Both indexOf
and for
loop will be O(n).
Just write a for
loop to compare each value in the list based on id
. That's the best way to go about here.
Upvotes: 1