This is a very straightforward task, but I feel I’m overlooking something. I have multiple objects that I’m trying to add to an ArrayList, and each of them has an identifying name in the form of a String. I need to be able to find (interact) with the objects in the ArrayList by calling the string name. So I tried this:
In my item class I have:
private String itemName;
public Item(String name)
{
itemName = name;
}
So I can give it a name to be used by the user.
Then in my class that interacts with the object, I create an ArrayList:
private ArrayList<Item> items = new ArrayList<Item>();
I add an object to the arrayList first by it’s actual object name, but I need to be able to interact with it using it’s String name, so I tried this:
public void removeItem(String itemName)
{
for (int i = 0; i < items.size(); i++)
{
if (items.get(i).toString() == itemName)
{
items.remove(i);
}
break;
}
}
But it’s not removing the item. If all of this is confusing, in essence I’m trying to create an OBJECT that I can give a STRING name (like I did with the item above), then have the ability to add the OBJECT to an ArrayList, and then finally be able to remove, or get, or do something with the OBJECTS in the ArrayList by calling the STRING name. I know I need to iterate through the ArrayList, but I can’t actually get the object.
Thanks for any help.
You are dong three mistakes here:
You are using
items.get(i).toString()which will not give youitemNamefor yourItem. It will just give you a string representation of yourItemclass, returned byObjectclass’stoStringmethod, if you don’t override one. However, this might work, if you have overriden atoStringmethod, and returned theitemNamefrom that. But, that I don’t see. And even if you have overriden that, I suggest you to have getter and setter for youritemNamefield, and use that to return theitemName.You are comparing strings using
==operator, which will not give you correct result. You should always compare the string usingequalsmethod.So, your
if statementshould look like:Listthat you are iterating upon. This will not work out, and may throwConcurrentModificationException. You should useIteratorto remove elements from theListwhile iterating.See for more details about those two problems, and how to solve them:
Further, you can consider overriding
equalsmethod in yourclass, and then you can directly compare your instances usingequalsmethod.Now, having pointed out the some logical problems with your code, it’s time to point out some design problems.
Given your requirement, it seems like you need to use a
HashMap, rather than aListof some custom type storing your attribute. You can create amaplike this:which will contain the mapping of
itemNameto respectiveItem, and then getting theItemfor a particular itemName is as simple asmap.get(itemName).