Say you have 10 indexed references within an object (#0 thru 9). However, 2 of them are unused in a particular instance of our class (say, #3 and #8). Here's my question: Memory and performance-wise, what would be the best option: an array of references of length 10, with null values at indices 3 and 8, or an list of size 8 coupled with an int array pointing to the indices of references in that list?
Solution 1 would look something like this:
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
}
}
Whilst solution 2 would be more like so:
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: is a null reference inside an array larger than an int?