courtney young wrote:Hi, I have to implement a grow and shrink method in java using loops but I'm lost! We aren't allowed to use things like .copy or .copyof or anything of that nature. Please help! Any advice on where to head would be great.
OK, try this.
You know that what you need to do is take an "old array" of size x and "grow" it to size y; and, as Pawel pointed out, to do that you need to:
1. Create a "new array" of size y.
2. Copy all the elements from "old array".
3. Replace "old array" with "new array".
My advice: Create a new GrowArray class that ONLY contains the things you need: an Array, a "current size", and a grow() method (you may not even need the second of those).
Right now (I suspect) you're distracted by all the "clutter" in your ArrayList class, and you need somewhere 'quiet' to work on this problem. Once you have it written and tested in GrowArray, and you KNOW it works, transfer it to your ArrayList class.
courtney young wrote:I think I might have got it:
Looks like it, but it's difficult to tell without seeing the whole class.
And BTW, the convention for generic types is to use a single letter, usually 'T' (for 'type') - but in your case, I might make it 'C', just to remind myself that it's a Comparable type.
Java's ArrayList class actually uses 'E' - for 'entry' (or possibly 'element').
Would it make sense to do:
so it will cut the array in half and put it in a new array or am I just hoping it would have been this simple to create a shrink method after my grow method?
I think I've figure out the first part of shrink:
This is as far as I've got. I'm confused. I know I need another loop here. I'm just not too sure about what needs to happen. Do I need to copy contents again in a new array of the new size?
You need to do:
1. Check if you need to shrink the array.
2. Calculate new size.
3. Create a new array with that size (update capacity!)
4. Replace the array with the new one.
My advice is: StopCoding (this is a link). Stop guessing. Turn off your computer. Think about the solution (a description, not a code!) and write it down on paper.
courtney young wrote:I'm confused. I know I need another loop here.