title: Finding number of pairs of integers in an ArrayList
body: <p>Recently bumped into a hackerrank challenge, got to find pair of int in a given array. 
  Using ArrayList as an approach.
  Can anyone rectify the errors in this code.</p>
  
  <p>Error :Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 9</p>
  
  <p>at java.util.ArrayList.rangeCheck(ArrayList.java:653)</p>
  
  <p>at java.util.ArrayList.remove(ArrayList.java:492)</p>
  
  <p>at Solution.main(Solution.java:32)</p>
  
  <pre><code>import java.io.*;
  import java.util.*;
  import java.text.*;
  import java.math.*;
  import java.util.regex.*;
  
  public class Solution {
  
      public static void main(String[] args) {
          Scanner in = new Scanner(System.in);
          int n = in.nextInt();
          int c[] = new int[n];
          for(int c_i=0; c_i &lt; n; c_i++){
              c[c_i] = in.nextInt();
          }
          int count=0;
  
          Arrays.sort(c);
  
          ArrayList&lt;Integer&gt; ch = new ArrayList&lt;&gt;();
  
          for(int c_i=0; c_i &lt; n; c_i++){
             ch.add(c[c_i]);
          }
  
          for(int i=0;i&lt;ch.size();i++){
              int a = ch.get(i);
              int b=ch.indexOf(a);
              if(b&lt;0)
                  continue;
              else{ 
                  ch.remove(a);
                  ch.remove(b);
                  count++;
                  for (int j=0;j&lt;ch.size()-2;j++){
                      ch.add(j,ch.get(j+2));
  
                  }
              }
              System.out.println(count);
          }
  
      }
  </code></pre>
  
  <p>Edited the above approach and while finding that <code>b</code> will give the index of <code>a</code> removing only one element always, so now tried the approach that the first element is removed no matter what and then searching for the matching pair element until the arrayList is empty.</p>
  
  <pre><code>while(ch.size()!=0){
          int a = ch.get(0);
          ch.remove(0);
          int b = ch.indexOf(a);
          if(b&lt;0){
  
              for (int j=0;j&lt;ch.size()-1;j++)
                  ch.add(j,ch.get(j+1));
              continue; 
              }
          else{ 
  
              ch.remove(b);
              count++;
              for (int j=0;j&lt;ch.size()-2;j++)
                  ch.add(j,ch.get(j+2));
              }
       }
  
  
  
  Error: Terminated due to timeout
  </code></pre>