Typo boy
Typo boy

Reputation: 85

Generic array index out of bounds

Ok , here is my problem . I'm learing to use generic classes and methods. I want to make an generic array list and method that will add/remove element by choosen index. I simply doesn't know how to do that . My example is calling an IndexOutOfBoundsException.

Any help is welcome. Thanks it advance .

class klasa3:

public class klasa3<E> {
    private java.util.ArrayList<E> list = new java.util.ArrayList<>();



   public klasa3(int initSize){ 

   }


   public int getSize() {
         return list.size();
   }

   public E peek() {
         return list.get(getSize() - 1);
   }

   public void push(E o,int indeks) {
       o = list.get(indeks);
       list.add(o);
   }

   public E pop(int indeks) {
         E o = list.get(indeks);
         list.remove(indeks);
        return o;
   }

   public boolean isEmpty() {
         return list.isEmpty();
   }

   @Override
   public String toString() {
           return "stack: " + list.toString();
   }
 }

main class:

public class klasa2 {
   public static void main(String[] args ) {


        klasa3 stak2 = new klasa3(13);
       stak2.push("cola",2);  // problem here
       stak2.pop(2);
        System.out.println(stak2.getSize()); 

   }


 }

Upvotes: 2

Views: 173

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500385

You're creating an empty ArrayList, and then trying to get the third element (element at index 2) from it within your push method. That's not going to work.

Now, you're currently ignoring your initSize parameter in your constructor. You might want something like:

// TODO: Rename the class to follow naming conventions
public klasa3(int initSize) { 
    for (int i = 0; i < initSize; i++) {
        list.add(null);
    }
}

Or provide a default element:

// TODO: Rename the class to follow naming conventions
public klasa3(int initSize, E element) { 
    for (int i = 0; i < initSize; i++) {
        list.add(element);
    }
}

Upvotes: 2

Jesper
Jesper

Reputation: 206796

This is what is happening:

In the main method you first create a new klasa3 object. Then you call push("cola", 2) on it.

The push method does: o = list.get(indeks), where indeks is 2. At this point the list is empty, so 2 is not a valid index, which causes an IndexOutOfBoundsException.

The index that you pass to the get method must be between 0 (inclusive) and the size of the list (exclusive). Since the size is 0, the index 2 is invalid.

Upvotes: 0

Related Questions