我试图创建一个stacks
它具有以下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
堆栈应该能够在需要时动态改变大小,所以客户端程序不要每次都这样做。
我已经完成了所有只有我的问题是分配对象A
对象B
并不意味着A
现在将指向B
的地址?
这里是我的代码,我希望它explaines我的意思
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;
}
虽然当前对象的已更新为什么运行在问题与旧的大小这一计划的结果。
一个问题是它可以分配this= newStacks
而不是实例化新Stacks object
没有在Java中分配'this'是不可能的。 'this'只能由JVM分配一次,并且它实际上是一个对象的最终变量。 –
您分配给本地变量/参数,不会修改调用者的变量... –
另外** Java集合框架**中已经有堆栈/队列,请参阅:http://docs.oracle.com/ javase/8/docs/api/java/util/Deque.html –