개체 (# 0에서 9까지) 내에 10 개의 색인 된 참조가 있다고합시다. 그러나 그 중 2 개는 클래스의 특정 인스턴스에서 사용되지 않습니다 (예 : # 3 및 # 8). 여기 내 질문은 다음과 같습니다. 메모리와 성능면에서 가장 좋은 옵션은 다음과 같습니다. 길이가 10 인 참조 배열과 인덱스 3과 8에 null 값이 있거나 배열 8을 가리키는 int 배열과 결합 된 크기 8의 목록 그 목록에있는 색인의 색인?개체 배열 대 색인 배열
용액 1은 다음과 같을 것이다 : 용액 2 하다니
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
}
}
보다과 같이 될 것이다 :
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 :는보다 어레이 내부 null 참조 크다 int?