Computer Science arrays help please

<p>What is the difference, if there is a difference at all between </p>

<p>d = new double[100];</p>

<p>and</p>

<p>double[] d = new double[100]; ?</p>

<p>the first one was declared in previous code. The second one is being declared and instantiated on the spot.</p>

<p>Also, how would you initialize an array with an unspecified number of elements in it?</p>

<p>Thank you!</p>

<p>You would have to do:</p>

<p>double[] d;</p>

<p>then, when you know how many elements you need,</p>

<p>d = new double[number];</p>

<p>

double d = null;
and d = new double[n] when you actually know.</p>

<p>Otherwise you might want to use a Collection, but that’s out of the scope of AP CS.</p>

<p>Or use an ArrayList…</p>

<p>

You won’t be able to do this on the FRQs, but if you were to initialize an array with elements 1,1,1 then you would put in </p>

<p>


int[] nums = {1,1,1};

</p>

<p>^ That’s just the same as doing an int[3]
If you truly didn’t know you should just do a int[large number]
and have a
int c = 0;
and do a
list[c++] = thisValue;
to keep adding on elements.</p>

<p>


int[] nums = {1,1,1}; //is on APCS exam

Array Initializers are tested on the APCS exam, so you are responsible for knowing this. A bit confusing is that anonymous arrays aren’t.


int[] nums = new int[]{1,1,1}; //not on APCS exam

</p>

<p>

</p>

<p>…and you will lose points on the APCS exam for suggesting this. Better would be to start out what you need and then create a new array of 50% or double size when you run out of room. (which is what ArrayList really does).</p>

<p>And exactly how would you lose points?</p>

<p>

The exam often asks a question about the best way of storing data. Creating a gigantic array and then only using a small part of it is a waste of heap (computer memory) storage.
Students are expected to know how to double the site of an array by using the new keyword.</p>

<p>I like how you change people’s words. Well done.</p>

<p>

</p>

<p>I apologize. I re-read my response to you and I see that it sounds like I’m dismissing your response. I was actually excited by your suggestion and really just wanted to talk about memory management questions for the APCS.</p>

<p>Some of the multiple choice questions ask students to weigh the cost of algorithms vs memory. For example, mergesort is faster than insertion or selection, but it requires double the memory. </p>

<p>I’ve seen many new students create a gigantic array because they don’t know how much of it will be used. If you honestly don’t know how much space to use, then create a small array and simply copy it to a new one when you run out of memory.</p>

<p>Of course, ArrayLists are not the only implementation of the List interface… there are other collections (like LinkedLists) that can be good too depending on what you want.</p>