title: Simple Java code using (implementing ArrayList as a stack) gives an error when running
body: <p>I finally managed to write my first Java assignment. The point of the assignment was to implement an ArrayList with Strings which was supposed to behave like a stack. </p>
  
  <p>However, when I run the code in Eclipse I get some kind of error saying: </p>
  
  <pre><code>Exception in thread "main" øv2.Stack@c723704
  java.lang.ArrayIndexOutOfBoundsException: -1
  at java.util.ArrayList.elementData(Unknown Source)
  at java.util.ArrayList.get(Unknown Source)
  at øv2.Stack.peek(Stack.java:30)
  at øv2.Stack.main(Stack.java:47)
  </code></pre>
  
  <p>I am not sure why this is happening, here is my code:</p>
  
  <pre><code>public class Stack {
  
      private ArrayList&lt;String&gt; stringList = new ArrayList&lt;String&gt;();
  
      RandomStringGenerator rsg = new RandomStringGenerator();
  
      private void push(String i){
          stringList.add(i);
          }
  
      private String Pop(){
          if (stringList.size() &gt;= 1){
              String positionInArray = stringList.get(stringList.size() - 1);
              stringList.remove(stringList.size() - 1);
              return positionInArray;
          }
  
          else {
              return null;
          }
  
      }
  
      private String peek(int i){
          if (i &gt;= 0 &amp;&amp; i &gt;= (stringList.size() - 1)){
              return stringList.get(stringList.size() - 1 - i);
          }
          else{
              return null;
          }
      }
  
      private int getSize(){
          return stringList.size();
      }
  
      public static void main (String [] args){
          Stack stack = new Stack();
          stack.push("1");
          stack.push("2");
          stack.push("3");
          System.out.println(stack);
          System.out.println(stack.peek(3));
          System.out.println(stack.Pop());
          System.out.println(stack);
      }
  
      }
  
  
  import java.util.Random;
  
  public class RandomStringGenerator {
  
  
      private int randomNumber;
  
      private Random randomNumberGenerator = new Random();
  
      public String randomStringGenerator(){
          int randomNumber = randomNumberGenerator.nextInt();
          String randomString = Integer.toString(randomNumber);
          return randomString;
      }
  
  }
  </code></pre>
  
  <p>Thank you for your time!</p>