简体   繁体   English

如何在 Java 中调整数组的大小?

[英]How to resize arrays in Java?

I have to write a method that inserts an integer into an already sorted integer array and another that removes an integer from that array.我必须编写一个方法,将一个整数插入到一个已经排序的整数数组中,另一个从该数组中删除一个整数。 Then I have to print out that same array.然后我必须打印出相同的数组。 Is is possible to make an array one element longer or shorter in Java?是否可以在 Java 中使数组一个元素更长或更短?

The code shown is the example from my homework.显示的代码是我作业中的示例。

public static void main(String[] args){
    int[] a1 = {-8,-5,-3,0, 3, 7, 10, 12,15, 22};
    System.out.println(Arrays.toString(a1));
    addInt(a1, 2);
    System.out.println(Arrays.toString(a1));
    addInt(a1, 13);
    System.out.println(Arrays.toString(a1));
    removeInt(a1,-5);
    System.out.println(Arrays.toString(a1));
    removeInt(a1, 10);
    System.out.println(Arrays.toString(a1));
    System.out.print(getInt(a1, 2));    //should output 0
}

I've tried setting my new array to the original array, a1, in my addInt method but when I run it, it just prints out the unmodified array.我已经尝试在我的 addInt 方法中将我的新数组设置为原始数组 a1,但是当我运行它时,它只是打印出未修改的数组。 I'm not allowed to use ArrayList.我不允许使用 ArrayList。

Edit: Resolved.编辑:已解决。 The assignment was made impossible on purpose as an exercise leading up to our introduction of ArrayList.作为导致我们引入 ArrayList 的练习,故意使分配变得不可能。

Guessing you wrote addInt something like this: addInt你写的addInt是这样的:

void addInt(int[] a, int n){
    int[] newArray = new int[a.length+1];
    System.arraycopy(a, 0, newArray, 0, a.length);
    newArray[a.length] = n;
    a = newArray;        // WRONG!
}

Method parameters in Java are passed by value , which basically means that a in addInt and a1 in the call addInt(a1, 2) are two separate variables.在Java方法参数由值来传递,这基本上意味着aaddInta1在呼叫addInt(a1, 2)是两个独立的变量。 Upon entry into addInt , a initially refers to the same array as a1 but beyond that there is no further relationship between a and a1 , and subsequently changing a to refer to something else has no effect on a1 .进入addInta最初引用与a1相同的数组,但除此之外, aa1之间没有进一步的关系,随后将a更改为引用其他内容对a1没有影响。

Your only option is to change addInt so that it returns the new array as a function result:您唯一的选择是更改addInt以便它将新数组作为函数结果返回:

int[] addInt(int[] a, int n){
    int[] newArray = new int[a.length+1];
    System.arraycopy(a, 0, newArray, 0, a.length);
    newArray[a.length] = n;
    return newArray;
}

and then call it like this:然后像这样调用它:

a1 = addInt(a1, 2);

You can't modify the array length.您不能修改数组长度。 when you create an array like int[] fixedLEngthArray = new int[n] you bassically reserved memory for n ints.当你创建一个像 int[] fixedLEngthArray = new int[n] 这样的数组时,你基本上为 n 个整数保留了内存。 if you need n+1 wou will have to create a new array into which to copy the old one and insert/remove the element.如果您需要 n+1,您将不得不创建一个新数组,将旧数组复制到其中并插入/删除元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM