Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating through hashmap and creating unique objects - trying to prevent duplicates
    primarykey
    data
    text
    <p>I explain what I am trying to do in comments above the parts in the method:</p> <pre><code>public int addPatron(String name) throws PatronException { int i = 0; //1. Iterate through a hashmap, and confirm the new name I am trying to add to the record doesn't already exist in the hashmap for (Map.Entry&lt;Integer, Patron&gt; entry : patrons.entrySet()) { Patron nameTest = entry.getValue(); //2. If the name I am trying to add already exists, we want to throw an exception saying as much. if (nameTest.getName() == name) { throw new PatronException ("This patron already exists"); //3. If the name is unique, we want to get the largest key value (customer number) already in the hash, an increment by one. } else if (nameTest.getName() != name) { Map.Entry&lt;Integer,Patron&gt; maxEntry = null; for(Map.Entry&lt;Integer, Patron&gt; entryCheck : patrons.entrySet()) { if (maxEntry == null || entryCheck.getKey() &gt; maxEntry.getKey()) { maxEntry = entryCheck; i = maxEntry.getKey(); i++; } } } else { throw new PatronException("Something's not working!"); } //4. If everything is ok up to this point, we want to us the name and the new customer id number, and use those to create a new Patron object, which then gets added to a hashmap for this class which contains all the patrons. Patron newPatron = new Patron(name, i); patrons.put(i, newPatron); } return i; } </code></pre> <p>When I try and run a simple unit test that will fail if I successfully add the same name for addPatron twice in a row, the test fails.</p> <pre><code>try { testLibrary.addPatron("Dude"); testLibrary.addPatron("Dude"); fail("This shouldn't have worked"); </code></pre> <p>The test fails, telling me the addPatron method is able to use the same name twice. </p> <p>@Jon Skeet:</p> <p>My Patron class looks like this:</p> <pre><code>public class Patron { //attributes private String name = null; private int cardNumber = 0; //operations public Patron (String name, int cardNumber){ this.name = name; this.cardNumber = cardNumber; } public String getName(){ return name; } public int getCardNumber(){ return cardNumber; } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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