如何在方法中重新初始化数组并在 main 中更新新的大小



我的老师给了我们的AP计算机科学课一个即将到来的测试的免费回答问题。问题说:

编写一个方法public static void insert(int[] a, int n, int x),在a的前n个元素中按顺序插入x,假设这些元素按升序排列。

所以实际上,她希望我们发送一个 x 值的数组,并得到一个包含 x + 1 值的数组。使用void函数时甚至可能吗?提前谢谢。

/**
 * Console output:
 * 
 * Array 'a' in insert method after inserting x: [4, 6, 7, 8]
 * Array 'a' in main method after insert has been called: [4, 6, 7]
 */
package chapter14Test;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class Chapter14Test
{
    public static void insert(int[] a, int n, int x)
    {
        //declare variables
        List<Integer> aList = new ArrayList<Integer>();
        Integer[] tempA = new Integer[a.length + 1];
        //traverse a and add values to aList
        for (int i = 0; i < a.length; i++)
        {
            //add a value to aList
            aList.add(a[i]);
        } //end for
        //traverse aList until n + 1 is reached
        for (int i = 0; i < n; i++)
        {
            //determine if aList value is greater than x
            if (aList.get(i).intValue() >= x)
            {
                //add x at index i
                aList.add(i, x);
                //exit loop
                i = n + 1;
            } //end if
        } //end if
        //determine if x needs to be added at the end
        if (x > aList.get(aList.size() - 1).intValue())
        {
            //add x to end of aList
            aList.add(x);
        } //end if
        //convert aList to an array
        tempA = aList.toArray(new Integer[0]);
        //reinitialize a
        a = new int[tempA.length];
        //transfer tempA values to a
        for (int i = 0; i < tempA.length; i++)
        {
            //transfer value at tempA element to a element
            a[i] = tempA[i].intValue();
        } //end for
        //display a
        System.out.println("Array 'a' in insert method after inserting x: " + Arrays.toString(a));
    } //insert
    public static void main(String[] args)
    {
        //declare array
        int[] a = new int[] {4, 6, 7};
        //insert 8 among the first two elements in a
        insert(a, 2, 5);
        //display a
        System.out.println("Array 'a' in main method after insert has been called: " + Arrays.toString(a));
    } //main
}

这是可能的。因此,当您编写以下语句时,您传递了a的地址或引用,因此您的insert方法所做的任何更改最终都会反映在main方法的数组a中。

insert(a, 2, 5);

插入方法将修改a。您不必将其退回。更改将反映在您的main方法中。

注意:如果必须放大a以存储新值,则不会发生这种情况。

最新更新