0

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!

5
  • Java don't have pointers. Commented Aug 12, 2014 at 8:34
  • yes, you can do the same thing with Java (well, by following the Java syntax) and let the GC worry about freeing your memory. Commented Aug 12, 2014 at 8:34
  • 1
    What are you calling "dynamic". To me, this term is related to data structures able to grow, unlike the arrays. Commented Aug 12, 2014 at 8:35
  • I completely agree with @Dici. You are still allocating data on the heap based on a value which is resolved at compile time. Commented Aug 12, 2014 at 8:37
  • In C++ we prefer std::vector<int> v(arraySize); because you don't have to delete it. Commented Aug 12, 2014 at 8:45

2 Answers 2

3

Yes you can. With small syntax correction,

int arraySize = 10; // may resolve at runtime even
int[] array = new int[arraySize]; 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

op is asking about allocating and freeing memory. here is the freeing memory part

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.