Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are dong three mistakes here:</p> <ul> <li><p>You are using <code>items.get(i).toString()</code> which will not give you <code>itemName</code> for your <code>Item</code>. It will just give you a string representation of your <code>Item</code> class, returned by <code>Object</code> class's <code>toString</code> method, if you don't override one. However, this might work, if you have overriden a <code>toString</code> method, and returned the <code>itemName</code> from that. But, that I don't see. And even if you have overriden that, I suggest you to have <em>getter</em> and <em>setter</em> for your <code>itemName</code> field, and use that to return the <code>itemName</code>.</p></li> <li><p>You are comparing strings using <code>==</code> operator, which will not give you correct result. You should always compare the string using <code>equals</code> method.</p></li> </ul> <p>So, your <code>if statement</code> should look like: </p> <pre><code> if (items.get(i).getName().equals(itemName)) </code></pre> <ul> <li>3rd problem is, you are trying to modify the <code>List</code> that you are iterating upon. This will not work out, and may throw <code>ConcurrentModificationException</code>. You should use <code>Iterator</code> to remove elements from the <code>List</code> while iterating.</li> </ul> <p><strong>See for more details about those two problems, and how to solve them:</strong></p> <ul> <li><a href="https://stackoverflow.com/q/513832/1679863">How do I compare strings in Java?</a></li> <li><a href="https://stackoverflow.com/q/223918/1679863">Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop</a></li> </ul> <p>Further, you can consider overriding <code>equals</code> method in your <code>class</code>, and then you can directly compare your instances using <code>equals</code> method. </p> <hr> <p>Now, having pointed out the some <em>logical problems</em> with your code, it's time to point out some <em>design problems</em>. </p> <p>Given your requirement, it seems like you need to use a <code>HashMap</code>, rather than a <code>List</code> of some custom type storing your attribute. You can create a <code>map</code> like this:</p> <pre><code>Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;(); </code></pre> <p>which will contain the mapping of <code>itemName</code> to respective <code>Item</code>, and then getting the <code>Item</code> for a particular itemName is as simple as <code>map.get(itemName)</code>.</p>
 

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