简体   繁体   English

Java等效于C ++中动态分配的数组

[英]java equivalent of dynamically allocated arrays in C++

I'm learning java after having programmed in C++ for a while, and I'm wondering if you can dynamically allocate an array in java as you do in C++. 在用C ++编程一段时间后,我正在学习Java,我想知道是否可以像在C ++中一样动态地在Java中分配数组。

Say in C++ we do: 说在C ++中,我们这样做:

int* array = new int[arraySize]; //allocate an array
delete[] array;                  //delete it

Can you do the same in java or is there a java equivalent that basically does the same thing? 您可以在Java中做同样的事情吗,或者有可以等效地做同样事情的Java等价物? Thanks! 谢谢!

Yes you can. 是的你可以。 With small syntax correction, 通过较小的语法校正,

int arraySize = 10; // may resolve at runtime even
int[] array = new int[arraySize]; 

You can create new arrays using 您可以使用创建新数组

int[] myNewArray = new int[myArraySize]; // myArraySize being an int

or use List like ArrayList which are resizable. 或使用可调整大小的ArrayList之类的 List。

In java, deletion is made by the garbage collector. 在Java中,删除是由垃圾收集器进行的。 So you usually don't call any methods to manually remove your objects. 因此,您通常不调用任何方法来手动删除对象。

To do so, you can simply change the reference to null 为此,您只需将引用更改为null

myNewArray = null;

The next time the garbage collector is called, it may delete the "array" object. 下次调用垃圾收集器时,它可能会删除“数组”对象。 You can also manually notiy the garbage collector using 您也可以使用以下方法手动通知垃圾收集器

System.gc();

But you can't be sure your object will be deleted at this time. 但是您不能确定此时是否将对象删除。

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

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