我在堆栈 class 中的 push() 改变了堆栈中的每个元素

my push() in stack class mutates every element in the stack

我制作了一个基于DataRecord 的堆栈数组。 两个 classes 编译都没有错误,但是当我对堆栈执行 push() 时,它会改变 stackArray[] 的每个索引中的数据。

我找不到造成此问题的代码行。 请帮我找出原因,谢谢

数据记录class:

public class DataRecord
{
    private String id;
    private String data;

    //default constructior
    public DataRecord( )
    {
        this.id = " ";
        this.data = " ";
    }

    //overloded constructor
    public DataRecord( String id, String data )
    {
        this.id = id;
        this.data = data;
    }

    //set method
    public void setIDandData( String id, String data )
    {
        this.id = id;
        this.data = data;
    }


    //get method
    public String getID()
    {
        return id;
    }
    public String getData()
    {
        return data;
    }

    //toString
    public String toString()
    {
        return "\n Your ID is : " + id +
                "\n Your DataRecord is : " + data + "\n";
    }
}//End of DataRecord

MyStack1 class:

class MyStack1
{
    private int maxSize;
    private DataRecord[] stackArray;
    private int top;
    private String tempString = "";

    public MyStack1(int sizeOfStack)
    {
        maxSize = sizeOfStack;
        stackArray = new DataRecord[maxSize];
        top = -1;
    }

    public void push( DataRecord userInput )
    {
        stackArray[++top] = userInput;
    }

    public DataRecord pop()
    {
        return stackArray[top--];
    }

    public String toString()
    {
        tempString = "";

        for(int i = 0; i <= top; i++)
        {
            tempString += i+1 + stackArray[i].toString();
        }
        return "\nThe max size of the stack is : " + maxSize +
                "\nThe top index of the stack is : " + top +
                "\nThe top element of the stack is : " + stackArray[top] +
                "\nThe list of element in the stack is : " +
                "\n" + tempString;
    }

    public static void main(String[] args)
    {
        MyStack1 stackArray = new MyStack1( 5 );

        DataRecord newData = new DataRecord(" Hello "," world! ");
        stackArray.push(newData);

        System.out.println("Results : " + stackArray.toString());

        newData.setIDandData("why","omg");
        stackArray.push( newData );

        System.out.println("Results : " + stackArray.toString());

        System.out.println("pop :"+stackArray.pop().toString());
        System.out.println("pop :"+stackArray.pop().toString());
    }
}

output looks like

当我编译运行时,输出如上图。

DataRecord newData = new DataRecord(" Hello "," world! ");
stackArray.push(newData);

System.out.println("Results : " + stackArray.toString());

newData.setIDandData("why","omg");
stackArray.push( newData );

newData.setIDandData修改您已经放入的对象。您必须明确创建一个新的DataRecord; Java 不会隐式复制对象。当您将 newData 压入堆栈时,它会压入对该对象的引用;在一处修改该对象仍会修改您放入堆栈的对象。

没有办法解决这个问题;这就是 Java 的工作原理。