0
假設您在對象中有10個索引引用(#0至9)。然而,其中2個在我們班的特定實例中未被使用(例如,#3和#8)。 這裏是我的問題: 內存和性能方面,最好的選擇是什麼:長度爲10的索引數組,索引爲3和8的空值,或者大小爲8的列表以及指向該列表中的引用索引?對象列表vs列表+索引數組
溶液1將看起來像這樣:
class SomeObject{
OtherObject[] references = new OtherObject[10];
{
for(int i = 0; i<10; i++){
if(i != 3 && i != 8)
references[0] = new OtherObject();
//otherwise just keep the null value
}
}
//then to use (here getting the toString() value)
String getStringOfObjectAtIndex(int index){
//in real code we'd first check that index is within 0-9
if(references[index] != null)
return references[index].toString();
else
return "";//no reference for that index
}
}
雖然溶液2會更喜歡這樣:
class SomeObject{
ArrayList<OtherObject> references = new ArrayList<>(0);
int[] pointers = new int[10];
{
for(int i = 0; i<10; i++){
if(i != 3 && i != 8){
pointers[i] = references.size();
references.add(new OtherObject());
}else{
pointers[i] = -1;//no reference available
}
}
}
//then to use (here getting the toString() value)
String getStringOfObjectAtIndex(int index){
//in real code we'd first check that index is within 0-9
if(pointers[index] != -1)
return references.get(pointers[index]).toString();
else
return "";//no reference for that index
}
}
TL; DR:比一個較大的陣列內的空引用詮釋?