简体   繁体   English

Java增加数组大小

[英]Java increase the array size

I have the following code that takes integers and stores it in a array of booleans according to the position. 我有以下代码,该代码采用整数并将其根据位置存储在布尔数组中。 I have a method include that allows the user to input more numbers into the array however if the number is bigger than the array size then I need to increase the size. 我有一个方法,其中包括允许用户向数组中输入更多数字的方法,但是如果该数字大于数组大小,则需要增加大小。 I am aware that you can't do much with arrays once they are made just change what's in each position. 我知道,一旦对数组进行更改,您就不能做很多事情,只需更改每个位置的内容即可。 Is there a quick way to make it bigger or could I use arraylists to keep the array size changing? 有没有快速的方法来增大它,还是可以使用arraylists来保持数组大小的变化?

public class ISet {
    public int max;
    boolean[] numArray;


    ISet(int a) {
        this.size = a;
        this.numArray = new boolean[size];

    }

    public void include(int n) {
        if (n > size) {
            this.size = n;
            numArray[n]=true;

        }
        else

            numArray[n]=true;


        }

If you want to make it bigger yourself you can use Arrays.copyOf(numArray, newLength) which will copy your array into a new new array of the specified length adding falses at the end if the new length is longer than the original. 如果您想自己做大一点,可以使用Arrays.copyOf(numArray, newLength)将数组复制到指定长度的新新数组中,如果新长度比原始长度长,则在末尾添加false。

Otherwise you can use an ArrayList. 否则,您可以使用ArrayList。

You should use an ArrayList. 您应该使用ArrayList。

Normal arrays have a fixed size in Java. 普通数组在Java中具有固定大小。

You can either simply use an ArrayList, although it'll have to be ArrayList<Boolean> as opposed to boolean (the primitive data type). 您可以简单地使用ArrayList,尽管它必须是ArrayList<Boolean>而不是boolean(原始数据类型)。 Probably the easiest solution. 可能是最简单的解决方案。

The other option would be to create a new, larger array and copy every element from the current array to the new one when the size of the current array is exceeded. 另一种选择是创建一个更大的新数组,并在超出当前数组的大小时将每个元素从当前数组复制到新数组。

For "normal" code you should use ArrayList instead. 对于“普通”代码,您应该改用ArrayList

For application that use extreme huge arrays, the array needs much less memory, than the ArrayList, because an Object needs 4 at least 4 times (16 bytes) more memory than a primitive. 对于使用极端巨大数组的应用程序,该数组比ArrayList所需要的内存要少得多,因为与原始对象相比,Object所需要的内存至少多4倍(16字节)。

For such special situations, you can use Arrays.copyOf() which copies the content into a new bigger array. 对于此类特殊情况,可以使用Arrays.copyOf()将内容复制到一个更大的新数组中。 See also src cocde of ArrayList.java 另请参见ArrayList.java src代码

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

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