2

I am learning the Stack Data Structure. I want to create a dynamic array. When the size is exceeded, I want to create a new array.

Program output:

java.lang.ArrayIndexOutOfBoundsException: 2
must be :50 40 30

The code is as given below:

    class Stack{
      int array[];
      int size;
      int top;

      Stack(int size){
        this.size=size;
        array=new int[size];
        top=0;
       }

       public void push(int a){
          if(top>=size){
          int array2[]=new int[size*2];
          for(int i=0;i<size;i++){
            array2[i]=array[i];
          }
          array[top++]=a;
          }
          else{
            array[top++]=a;
          }
        }
        public int pop(){
          return array[--top];
      }
    }

    public class Stack1 {

    public static void main(String[] args) {
       Stack y=new Stack(2);
       y.push(10);
       y.push(20);
       y.push(30);
       y.push(40);
       y.push(50);

       System.out.println(y.pop());
       System.out.println(y.pop());
       System.out.println(y.pop()); 
    }
 }
2
  • Code formatting and grammatical errors removed. Commented Dec 4, 2016 at 14:41
  • Sorry. I learned accept answer. I not good english but ı learning english.Thanks Commented Dec 4, 2016 at 15:01

1 Answer 1

2

You are creating a new array with a doubled size when the original array is full, but then you do nothing with the new array.

Change your code to :

public void push(int a){
  if(top>=size){
    int array2[]=new int[size*2];
    for(int i=0;i<size;i++){
      array2[i]=array[i];
    }
    array = array2; 
    size *=2;
  }
  array[top++]=a;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.