我有一个对象数组。当数组填满时,我想创建一个新数组,其大小是旧数组的两倍,并将所有元素转移过来。我做错了,我认为这与我没有创建对新数组的正确引用有关。这是我的代码,任何帮助解决这个问题的人将不胜感激。
private int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
private int numberOfElements = 0;
public int getNumOfElements(){
return numberOfElements;
}
public void setDirectorySize(int size){
DIRECTORY_SIZE = size;
}
public int getDirectorySize(){
return DIRECTORY_SIZE;
}
public void addEntry(String surname, String initial, String num) {
// TODO add an entry to an array, also increments numberOfElements variable tracking whats in array
if(getNumOfElements() == getDirectorySize()){ // if array is full
doubleArraySize(); // put temp values into new bigger directory array
}
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
numberOfElements++;
}
private void doubleArraySize(){
Entry[] temp = new Entry[DIRECTORY_SIZE]; //make new temp array same size as old one
for(int i = 0; i < DIRECTORY_SIZE ; i++){
temp[i] = directory[i]; // cycle through array putting all values into temp
// works up to here
}
setDirectorySize(DIRECTORY_SIZE*2); // double size of array
Entry[] directory = new Entry[DIRECTORY_SIZE]; // create new, double size directory array
for(int i = 0; i < temp.length ; i++){
directory[i] = temp[i];
}
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
最佳答案
在 doubleArraySize() 函数中,这就是问题:
Entry[] directory = new Entry[DIRECTORY_SIZE];
// you are not assigning it to the class attribute directory
// instead you are creating a local array directory
进行以下更改:
this.directory = new Entry[DIRECTORY_SIZE];
// this will assign the newly created array to the class attribute
注意:我个人更喜欢使用此指针来引用类属性,这样可以使我的代码更具可读性,并且每个人都清楚所讨论的变量是类属性而不是局部变量。
**此时 SIZE 已经翻倍了。无需乘以2
关于java - 如果数组已满,则将数组大小加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23023079/