title: Swapping string position in Arraylist java
body: <p>I have a sentence: Humpty Dumpty sat on a wall. 
  I want the strings to swap positions such that : Dumpty Humpty on sat wall a.</p>
  
  <p>So the code that I wrote is following : </p>
  
  <pre><code>import java.util.*;
  public class Swap{
  public static void main(String []args) {
      ArrayList&lt;String&gt; sentence = new ArrayList&lt;String&gt;();
      sentence.add("Humpty");
      sentence.add("Dumpty");
      sentence.add("sat");
      sentence.add("on");
      sentence.add("a");
      sentence.add("wall");
  
      int size = sentence.size() ; // for finding size of array list
      int numb ; 
  
      if(size%2 == 0) {
          numb = 1;
      }
      else {
          numb = 0;
      }
  
      ArrayList&lt;String&gt; newSentence = new ArrayList&lt;String&gt;();
  
      if(numb == 1) {
          for(int i = 0; i &lt;= size ; i = i+2) {
              String item = sentence.get(i);
              newSentence.add(i+1, item);
          }
  
          for(int i =  1; i&lt;=size ; i = i+2) {
              String item2 = sentence.get(i);
              newSentence.add(i-1, item2);
          }
  
  
          System.out.println(newSentence);
      }
  
      else {
          System.out.println(sentence);
      }
  
      }
  }
  </code></pre>
  
  <p>The code is compiling correct but when I run it, its giving an error.
  What i understand of this is that I am adding strings to the array list leaving positions in between. Like adding at position 3 without filling position 2 first. How do I overcome this problem ? </p>