如何修改构造函数内部全局数组的大小



如果槽已满,则需要将数组中的槽数增加一倍。我的代码目前位于我的层次是

public class Stack {
   Object filearray[]= new Object [5];
   public Object push(element) {
       if (filearray[filearray.length - 1] != null) {
            Object temp_array[] = new Object[filearray.length*2];
            int origonal = filearray.length*2;
            //adding the element that the user passed in
            temp_array[0] = element;
            for(int i =0; i<filearray.length;i++) {
                temp_array[i+1] =filearray[i];
            }
            //wiping the filearray clear
            Object filearray[] = new Object [origonal];
            for (int i=0; i<temp_array.length; i ++) {
                filearray [i]=temp_array[i];
            }
            return filearray;
        }
    }
}

新的双大小数组永远不会保留在实例中,所以请查看以下内容来修复它:

public Object push(element)
{
    if (filearray[filearray.length - 1] != null)
    {
        Object temp_array[] = new Object[filearray.length*2];
        int origonal = filearray.length*2;
        //adding the element that the user passed in
        temp_array[0] = element;
        for(int i =0; i<filearray.length;i++)
        {
            temp_array[i+1] =filearray[i];
        }
        this.filearray = temp_array;
    }
}

您不需要擦除旧数组,只需将其引用更改为新分配的数组。

在上面的代码中,您创建了一个新的本地数组,作用域为该方法。你没有改变原来的类成员。:

    //wiping the filearray clear
    Object filearray[] = new Object [origonal];

创建一个隐藏类成员的数组filearray。您只需要创建临时数组,然后执行:

    filearray = temp_array;

交换引用。

我可能会研究ArrayList,因为它会在幕后完成所有这些,以及(不相关的)Java泛型,因为它会给你类型安全(除非你真的想要存储Objects)

最新更新