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());
}
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.