我在stack类中的push()会改变堆栈中的每个元素

时间:2015-10-09 17:56:52

标签: java arrays class methods stack

我创建了一个基于DataRecord的堆栈数组。 这两个类都编译时没有错误,但是当我将push()写入堆栈时,它会改变stackArray []的每个索引中的数据。

我无法找到导致此问题的代码行。 请帮助我找到原因,谢谢。

DataRecord类:

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

编译运行时,输出如上图所示。

1 个答案:

答案 0 :(得分:2)

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的工作原理。