title: How to remove Duplicate objects from Java ArrayList?
body: <p>I need your help with some sample code for a situation I could not get free from.
  I have a simple list of objects. My class is like this:</p>
  
  <pre><code>class MyClass {
      String str;
      Integer intgr;
  }
  </code></pre>
  
  <p>And the list contains elements like:</p>
  
  <pre><code>[{a1  5}, {b2  3}, {g1  1}, {b5  1}, {c9  11}, {g2  3}, {d1  4}, {b3  19}... ... ...]
  </code></pre>
  
  <p>I need to check if any element contain the same prefix in string (here suffix is the last single character) then keep that element which have greater value in integer. The expected output from the above example list will be:</p>
  
  <pre><code>[{a1  5}, {c9  11}, {g2  3}, {d1  4}, {b3  19}... ... ...]
  </code></pre>
  
  <p>Strings will have unique values but could have matches in prefix. I'm not that good in java. So can anybody help me out from this? Here is the code I'm trying but getting <code>IndexOutOfBoundsException</code>. This code has faults, so need some help from you.</p>
  
  <p>Thanks!</p>
  
  <pre><code>        int size = list.size();
          for (int j = 0; j &lt; size; j++) {
          if (list.get(j).str.substring(0, list.get(j).str.length()-1).compareTo(list.get(j+1).str.substring(0, list.get(j+1).str.length()-1)) == 0) {
              if (list.get(j).intgr &gt; list.get(j+1).intgr)
                  list.remove(list.get(j+1));
                  size--;
              else {
                  list.remove(list.get(j));
                  j--;
                  size--;
              }
          }
      }
  </code></pre>