Create a Dynamic Array for Stack structure in Java - java

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;
}

Related

Java Q. How can I do insert&delete&print in Two Dimensional Array

Java Q. How can I do insert & delete & print in Two Dimensional Array...
How I can do it in
Two Dimensional
like this
private int [] [] arr = new int [3] [3];
If I do it in 1D array like this
public class List {
private int [] arr=new int[1000];
private int size=0;
public void add(int e){
arr[size]=e;
size++;
}
public void dispaly(){
for(int i=0;i<size;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public void insert(int e,int pos){
if (pos<=size){
size++;
for(int i=size;i>pos;i--)
arr[i]=arr[i-1];
arr[pos]=e;
}
else System.out.print("unbounded ..");
}
public void delete(int e){
int pos=locate(e);
if (pos!=-1){
for(int i=pos;i<size-1;i++)
arr[i]=arr[i+1];
size--;
}
}
+++++++++++++++++++++++
List list=new List();
list.add(10);
list.add(2);
list.add(40);
list.delete(103);
list.dispaly();
You can use nested "for" loops to print the array. The first for handling the row number, and the second handling the column number.

Does assigning an object to another mean that instant variables will aslo change?

I am trying to to create a stacks which has the following API:
Stacks(int n)// creates stacks of size n
pop() //returns the last element pushed in the stacks
pop(int n) //returns an array of of n elements
push(int e) //appends an element to the stacks
push(int n, ar[]) //appends an array to the stack
The stacks should be able to dynamically change size when needed, so client programs dont have to do it every time.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
Here is my code and i hope it explaines what i mean
public class Stacks {
/*
* constructs a stack object
* #param n that will determine that size of the stacks to be constructed
*/
public Stacks(int n)
{
this.elemetns= new int[n];
this.size=n;
this.top=-1;
}
/*
* constructs a stack object, with size of 2 when no parameter is given
*/
public Stacks()
{
this.elemetns= new int[2];
this.size=2;
this.top=-1;
}
public int pop()
{
if (top<0)
{
System.out.println("Error code 2: Empty stacks");
return -1;
}
else
{
int n= this.elemetns[top];
top--;
return n;
}
}
public int [] pop(int size)
{
if (this.size<size)
{
System.out.println("Error code 3: The Maximum number of elements that can be acquired is "+ this.size);
return null;
}
else
{
int res[]= new int[size];
for (int i=0;i<size;i++)
{
res[i]=pop();
}
return res;
}
}
public void push(int e)
{
if (!isFull())
{
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
else
{
updateStacksSize(this);
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
}
public void push(int n,int [] ar)
{
for (int i=0;i<n;i++)
this.push(ar[i]);
}
private void updateStacksSize(Stacks s)
{
int newSize= s.top*2;
Stacks newStacks= new Stacks(newSize);
for (int i = s.top; i>-1;i--)
newStacks.elemetns[i]=s.pop();
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
}
private boolean isFull(){return this.size==(this.top+1);}
public static void main(String[] args)
{
Stacks s= new Stacks(5);
for (int i=0;i<7;i++)
s.push(i+1);
System.out.println();
int []arr= s.pop(6);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
private int elemetns[];
private int top;
private int size;
}
Why does running this program results in problem with the old size although the current object's has been updated.
one more question is it possible to assign this= newStacks instead of instantiating new Stacks object
In Java you assign object references to variables.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
It is the other way around since the assignment in Java is from right to left.
"I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?"
if this is what you meant then:
Stacks A = new Stacks();
Stacks B = A;
Then what this means is that B is now pointing to A.
You're kinda over do it. A stack should consist of a chain of nodes, like an singel-linked list of nodes. I've written an example on this below, see if you can see how it works.
public class Stack <E> {
private StackItem<E> currTop;
private int size;
private int max;
private static class StackItem<E> {
private E e;
private StackItem<E> next;
}
public Stack(int max) {
currTop = null;
size = 0;
this.max = max;
}
public void add(E e){
if ((size+1) == max) throw new StackOverflowError("Max items in stack is reached");
StackItem<E> old = currTop;
currTop = new StackItem<>();
currTop.e = e;
currTop.next = old;
size++;
}
public E getFirst() {
if (currTop == null) return null;
E output = currTop.e;
currTop = currTop.next;
size --;
return output;
}
public E showFirst() {
return currTop.e;
}
public int getSize() {
return size;
}
}

After creating a bigger array, how do I use the new array in other functions of the same class?

It was asked of us to implement this class without built-in functions or Arraylist.
When needing to make the data array bigger, I created a new array and gave it a new size (which is the capacity+10). As the data array is a data member, I can access it from the other functions of the array. However, I can't access the newArray. Can I create a bigger array using the data array? If not,how can I access the new Array from the other functions of the class?
package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int data[];
int size;
int capacity;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;
}
public DynamicIntgerArray(int ca){
size=0;
if(ca<5)
capacity=5;
else
capacity=ca;
data=new int[capacity];
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
arry2=arry1;
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
}
}
public void getElement (int index){
}
public int getlength(){
return capacity;
}
public void insertElement(int element){
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
}
}
This is the code that was given to us that we have to work with that we cannot modify:
package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int [] data;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;}
public DynamicIntgerArray(int ca){
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
}
}
public void getElement (int index){
}
public int getlength(){
}
public void insetElement(int element){
checkCapacity(size+1);
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
if(checkIndex(index)){
checkCapacity(size + 1);
}
}
}
After this code:
int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
you need this little piece of magic:
data = newArray;
well, I hope you understand it is not magic at all.
You should have to create a new array and then reference data array to it like this way
int oldItems[] = new int[10];// this is your data array
int newItems[] = new int[20];// this is new array created
System.arraycopy(oldItems, 0, newItems, 0, 10);// copy new array to data array
oldItems = newItems;// your data saved and size increased of data array

Inserting into a simple Array and Deleting

public class DataOperations {
int arraySize=50;
int[]array=new int[arraySize];
public void generateRandomArray(){
for(int i=0;i<arraySize;i++){
array[i]=i;
}
}
public int getValueAtIndex(int index){
if(index<arraySize){
System.out.println("Your value At index "+index+" is "+array[index]);
return array[index];
}else{
System.out.println("Please Return an Index that is inbounds");
return 0;
}
}
public boolean doesArrayContainValue(int searchValue){
boolean valueInArray=false;
for(int i=0;i<arraySize;i++){
if(array[i]==searchValue){
valueInArray=true;
}
}
return valueInArray;
}
public void deleteIndex(int index){
if(index<arraySize){
for(int i=index;i<(arraySize-1);i++){
array[i]=array[i+1];
}
}
System.out.println(arraySize);
arraySize--;
System.out.println(arraySize);
}
public void printArray(){
for(int i=0;i<arraySize;i++){
System.out.print(i+"-");
System.out.println(array[i]);
}
}
public void insertValue(int index){
if(index<arraySize){
array[arraySize]=index;
System.out.println(arraySize);
arraySize++;
System.out.println(arraySize);
}
}
public void linearSearchForValue(int value){
boolean valueInArray=false;
System.out.println("The was Found and is at Index:");
for(int i=0;i<arraySize;i++){
if(array[i]==value){
System.out.println(i);
}
}
}
}
Hey So I created simple add and delete methods to my array. However, I am unsure about a couple parts. I Understand the add method, and that we are decreasing the arraySize from 50 to 49 for this specific array object that I created in my Driver class below. However, I am not sure why I cannot do my add method before my delete method insertValue method if I put arraySize++ before array[arraySize]=index, and did not call my deleteIndex method shouldnt my arraySize=51? but this throws an out of bounds exception
Driver Class Below
public class Driver {
public static void main(String[] args) {
DataOperations array=new DataOperations();
array.generateRandomArray();
array.insertValue(20);
array.printArray();
}
}
int arraySize=50;
You create an array of size 50. Arrays are of fixed size hence you cannot get an array of size 51. In your code, when adding/deleting an element from the array, you arent changing the size of the array. You are just moving the index to get your desired output. If you want a bigger array you can:
Create a new array of required size and copy all elements from old to new
Use ArrayList instead of arrays.

Initialization of class array

class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help
You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}
You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}
max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){

Categories