title: Rearranging arrays - java
body: <p>I'm trying to rearrange my Person array according to age from youngest to eldest using the code below.</p>
  
  <pre><code>public class Trial {
  
      public static void main(String[] args){
  
          Person[] person = new Person[3];
  
          person[0] = new Person("Jerome", 21);
          person[1] = new Person("Jam", 16);
          person[2] = new Person("Imelda", 53);
  
          for(int i=0; i&lt;person.length;i++){
              System.out.println(person[i].getName() + " " + person[i].getAge());
          }
  
          String name = "";
          int age = 0;
          int counter = 0;
  
          for(int i=1;i&lt;person.length;i++){
  
              name = person[i].getName();
              age = person[i].getAge();
  
              counter = i - 1;
  
              while(i&gt;-1&amp;&amp;person[counter].getAge()&gt;age){
                  person[counter+1].setAge(person[counter].getAge());
                  person[counter+1].setName(person[counter].getName());
                  counter -= 1;
              }
  
  
              person[counter+1].setAge(age);
              person[counter+1].setName(name);
  
          }
  
          for(int i=0; i&lt;person.length;i++){
              System.out.println(person[i].getName() + " " + person[i].getAge());
          }
  
      }
  }
  </code></pre>
  
  <p>The algorithm runs smoothly with arrays of integer but here, I get this error.</p>
  
  <pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
      at com.example.java.Trial.main(Trial.java:28)
  </code></pre>
  
  <p>This is where the error points to</p>
  
  <pre><code>while(i&gt;-1&amp;&amp;person[counter].getAge()&gt;age){
                  person[counter+1].setAge(person[counter].getAge());
                  person[counter+1].setName(person[counter].getName());
                  counter -= 1;
              }
  </code></pre>
  
  <p>Am I doing something wrong? Or is there another way of arranging object arrays according to a specific variable?</p>