I'm developing an app that uses ArrayList to fill ListView. I use custom Class for my ListView. I want to add/delete from ArrayList for my Listview.My aim to this app is control list item elements, if it is exist in ArrayList remove or if it is not exist in ArrayList add list item.
In order to explain my situation I have pasted my code below;
It is my custom Class;
public class NDListItem {
String textdata;
public NDListItem(String textdata) {
this.textdata = textdata;
}
}
It is my method for using my class. Name parameter is coming from another activity. It comes properly. I use for loop for this issue and could not afford to get what I want to do. I read some documentation and found another solution. Using equals and hash-code method for my class may be will do my job but I don't know how to do this usage.
EDIT : Add some explanation and myItems explanation in the second code block.
public void addLayersection(String name) {
//MyList already defined on the scope..
//MyList looks like this
// ArrayList<NDListItem> myItems = new ArrayList<>();
NDListItem listItem = new NDListItem(name);
if (myItems.size() == 0) {
myItems.add(listItem);
} else {
if(myItems.contains(listItem))
{
myItems.add(listItem);
}
else
{
myItems.remove(listItem);
}
}
myAdapter.notifyDataSetChanged();
}
EDIT2
I updated my Class for equals method. It works wonderfully but only work first item that I added to ArrayList. I want to this work for every items
public class NDListItem {
String textdata;
public NDListItem(String textdata) {
this.textdata = textdata;
}
public boolean equals(Object o) {
if (o == null) return false;
//if(!(o instanceof) NDListItem) return false;
if (!(o instanceof NDListItem)) return false;
NDListItem other = (NDListItem) o;
if (!this.textdata.equals(other.textdata))
return false;
else
return true;
}
}