Partially Filled Arrays – Intro to Java Programming

One challenge when using arrays is that the length is fixed. So let’s say that you need to collect some numbers and you don’t quite know how many, you’re going to have to make an array that’s large enough to hold them all. But then you may have fewer numbers in the array. Then it can hold. We say such an array is partially filled, just like this beaker over here. You wouldn’t want it to be filled up all the way to the rim. And in this situation you need to keep track of two things. You need, the overall length of the array. So here I’ll assume I’ll never have more than 1000 numbers. I allocate my array to have this length and then I keep a companion variable that I call the size that tells me how many elements I currently have. Right now, I don’t have any. Whenever I need to insert a new element, I execute this code here. I move the new value into values in bracket size, and then I increment the size. For example, to insert the very first element, size is 0, values bracket 0, is now initialized, and the size becomes 1. The next time, values of 1 Gets filled and so on. Now what happens if I fill up the array with a thousand values and then want to add the thousand and first. Let’s have a look at that situation. So here I have my partially filled beaker. I fill in more and more, and eventually when it gets full, what choice do I have? I have to get a bigger one and pour everything into that. It’s the same with partially filled arrays. So, here’s my array. It’s almost full. Now it’s completely full. I’d like to add another element. So, I’ll get myself an array that’s twice as long, copy over all the values, and now I can forget about the old array, and insert my next element over here. Of course, one can program that by hand, but as it happens There’s a library function that does the work for us. Here it is. The copyOf function takes an array and then the desired length of the larger array. It then makes the larger array and copies the original one in there, returns the large array, and we just capture it here again. So that’s what you’d have to do if you’re ever faced with a situation Where you want to collect an arbitrary number of values. It’s that kind of thing that makes you appreciate the array lists where you never have to worry about growing an array.

One thought on “Partially Filled Arrays – Intro to Java Programming

Leave a Reply

Your email address will not be published. Required fields are marked *