Note that there are some explanatory texts on larger screens.

plurals
  1. POJava ArrayList: Adding object using string name
    primarykey
    data
    text
    <p>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:</p> <p>In my item class I have: private String itemName;</p> <pre><code>public Item(String name) { itemName = name; } </code></pre> <p>So I can give it a name to be used by the user. </p> <hr> <p>Then in my class that interacts with the object, I create an ArrayList:</p> <pre><code>private ArrayList&lt;Item&gt; items = new ArrayList&lt;Item&gt;(); </code></pre> <p>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:</p> <pre><code>public void removeItem(String itemName) { for (int i = 0; i &lt; items.size(); i++) { if (items.get(i).toString() == itemName) { items.remove(i); } break; } } </code></pre> <p>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. </p> <p>Thanks for any help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload