I have small issue in arraylist android, let me tell you where i’m facing the issue.
I have a custom contact object, which holds the details about name, contact number and a unique ID. when i query the database i get the list and i will be storing in an ArrayList.
Here how i do
Arraylist<contact> ctlist = new Arraylist(contact);
ctlist = getitemfromDB();
in the next scenario, i do query and get some set of contact object based on certain condition. i get
again contact list objects.
Arraylist<contact> newctlist = new Arraylist(contact);
newctlist = getitemfromDB(condition);
Now, if i pick any object from newctlist and search in ctlist, though the object is present in ctlist
compiler says object not found.
may i know what is wrong with the above way, if i search inside same list i.e if i pick an object from newctlist and search in it, i will get correct expected result.
what would be the problem.
As told by Mitch Wheat, you are trying to compare two different objects. That’s because List uses
equalsmethod to retrieve specific object. I think you didn’t override it in your custom class.Just implement
equalsandhashCodemethods based on fields in your contact class.In fact, you should try to always override
equalsandhashCodemethods in classes where equality have a different meaning than just reference equality, e.g. beans. Please have a look there and there. Moreover, if you can, read chapter three from Josh Bloch’s “Effective Java” which contains quality rules for those implementations (By the way, read the whole book, it’s great).Please note that there are librairies helping you implementing correctly those (Java7
java.util.Objects, GuavaObjects, apache commonsEqualsBuilderandHashCodeBuilder)Be careful as those methods must have very precise mathematical property