java automatically doubling array size
質問
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.
解決
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);
}
}
他のヒント
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.
Size is only multiplying the size number, not double the array size. Try:
records = Arrays.copyOf(records, records.length*2);
所属していません StackOverflow