title: Java - Removing duplicates in an ArrayList
body: <p>I'm working on a program that uses an <code>ArrayList</code> to store <code>Strings</code>. The program prompts the user with a menu and allows the user to choose an operation to perform. Such operations are adding Strings to the List, printing the entries etc. What I want to be able to do is create a method called <code>removeDuplicates()</code>. This method will search the <code>ArrayList</code> and remove any duplicated values. I want to leave one instance of the duplicated value(s) within the list.  I also want this method to return the total number of duplicates removed. </p>
  
  <p>I've been trying to use nested loops to accomplish this but I've been running into trouble because when entries get deleted, the indexing of the <code>ArrayList</code> gets altered and things don't work as they should. I know conceptually what I need to do but I'm having trouble implementing this idea in code.</p>
  
  <p>Here is some pseudo code:</p>
  
  <p>start with first entry;
  check each subsequent entry in the list and see if it matches the first entry;
  remove each subsequent entry in the list that matches the first entry;</p>
  
  <p>after all entries have been examined, move on to the second entry;
  check each entry in the list and see if it matches the second entry;
  remove each entry in the list that matches the second entry;</p>
  
  <p>repeat for entry in the list </p>
  
  <p>Here's the code I have so far:</p>
  
  <pre><code>public int removeDuplicates()
  {
    int duplicates = 0;
  
    for ( int i = 0; i &lt; strings.size(); i++ )
    {
       for ( int j = 0; j &lt; strings.size(); j++ )
       {
          if ( i == j )
          {
            // i &amp; j refer to same entry so do nothing
          }
  
          else if ( strings.get( j ).equals( strings.get( i ) ) )
          {
             strings.remove( j );
             duplicates++;
          }
       }
   }
  
     return duplicates;
  }
  </code></pre>
  
  <p><strong>UPDATE</strong>: It appears that Will is looking for a homework solution that involves developing the algorithm to remove duplicates, rather than a pragmatic solution using Sets. See his comment:</p>
  
  <p>Thx for the suggestions. This is part of an assignment and I believe the teacher had intended for the solution to not include sets. In other words, I am to come up with a solution that will search for and remove duplicates without implementing a <code>HashSet</code>. The teacher suggested using nested loops which is what I'm trying to do but I've been having some problems with the indexing of the <code>ArrayList</code> after certain entries are removed.</p>