0

trying to initialize my array at 1 and have it double every time it's input fills up. this is what i have right now

int max = 1;
 PhoneRecord[] records = new PhoneRecord[max];
      int numRecords = 0;
      int size = Integer.parseInt(length.records[numRecords]);
 if (size >= max) {
   size = 2*size;
 }

but it's clearly full of fail. any suggestions or guidance would be great, thanks.

Evan Lemmons
  • 807
  • 3
  • 11
  • 27

3 Answers3

1

Why not use an ArrayList ? It'll exhibit very similar characteristics automatically.

From the private grow() method:

int newCapacity = oldCapacity + (oldCapacity >> 1);

You can't override the growth behaviour, but unless you really require a doubling due to your app characteristics, I'm sure it'll be sufficient.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

OK, you should use an ArrayList, but several other folks already told you that.

If you still want to use an array, here's how you'd resize it:

int max = 1;
PhoneRecord[] records = new PhoneRecord[max];
int numRecords = 0;

void addRecord(PhoneRecord rec) {
    records[numRecords++] = rec;
    if(numRecords == max) {
        /* out of space, double the array size */
        max *= 2;
        records = Arrays.copyOf(records, max);
    }
}
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • getting this error talking about the "void addRecord(PhoneRecord rec) { – Evan Lemmons Oct 16 '12 at 12:52
  • File: D:\School\CSC 2310\Book Progs\PhoneDirectory.java [line: 31] Error: Syntax error on token(s), misplaced construct(s) File: D:\School\CSC 2310\Book Progs\PhoneDirectory.java [line: 31] Error: Syntax error, insert ";" to complete Statement getting this error talking about the void addRecord(PhoneRecord rec) line – Evan Lemmons Oct 16 '12 at 12:53
1

Size is only multiplying the size number, not double the array size. Try:

            records = Arrays.copyOf(records, records.length*2);
PbxMan
  • 7,525
  • 1
  • 36
  • 40