简体   繁体   中英

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++.

Say in C++ we do:

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? 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.

In java, deletion is made by the garbage collector. So you usually don't call any methods to manually remove your objects.

To do so, you can simply change the reference to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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