gpt4 book ai didi

java - 堆栈模拟不存储元素

转载 作者:行者123 更新时间:2023-12-02 06:36:50 25 4
gpt4 key购买 nike

public class Stack {
Student Sarray[] = new Student[1000];
int nrElem=0;

public Student[] getAll(){
return this.Sarray;
}

public void push(Student x){

this.nrElem++;
this.Sarray[this.nrElem]=x;
}
}

我尝试手动实现堆栈,但遇到了一个小问题。当我插入另一个元素时,我插入的第一个元素会被存储和替换。我做错了什么?

public class Ctrl {
Stack x = new Stack();
public void addC(Student s){
if(findById(s.getId()) != null) {
System.out.println("Err!Duplicate id!/n");
} else {
if(s.getGrade()>10)
System.out.println("Err!Grade bigger than 10!/n");
else{
x.push(s);
}
}
}



public Student findById(int id){
Stack y=new Stack();
y=x;
Student z= new Student() ;

for(int i=1;i<=y.getNrElem();i++){
z=y.pop();
if (z.getId()==id)
return z;
}
return null;
}

2 个不同的 Stack 和 Ctrl 模块。

最佳答案

public Student findById(int id) 中,您执行以下操作:

Stack y=new Stack(); // creates new reference to new Stack ...
y=x; // reference is redirected to point to the class's Stack instance

y 现在指向类成员 x,您在下面的 for 循环中将其弹出为空。这意味着,如果您使用 ref y 对数据结构进行更改,则使用 ref x 将会看到这些更改,因为您是在同一实例上进行更改。

您可以在堆栈类中实现搜索,但不会更改堆栈的内容,或者您​​可以在堆栈的副本上实现此搜索。大多数情况下,这是通过在 DataStructure 类中提供“Copy”构造函数或“clone()”方法来实现的。

例如将上面的行更改为

Stack y = new Stack(x);
// y=x We do not need this any more.

并在 Stack 类中添加:

public Stack( Stack aStack ) {
System.arraycopy(aStack.Sarray,0,this.Sarray,0,aStack.Sarray.length);
// By the way: please start members with a small letter!

this.nrElem = aStack.nrElem;
}

附注:请注意 RamonBoza 的评论,为他+1。

关于java - 堆栈模拟不存储元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19562332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com