While going through the Effective Java examples, I failed to understand below code. How this anonymous Abstract class return List of objects without iterating through array elements or calling the add() method.
what's going on behind the scenes in below code?
public static void main(String[] args) {
int a[] = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
List<Integer> list = intArrayAsList(a);
System.out.println(list);
}
static List<Integer> intArrayAsList(final int[] a) {
if (a == null) {
throw new NullPointerException();
}
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return a[index];
}
@Override
public int size() {
return a.length;
}
@Override
public Integer set(int index, Integer element) {
int oldVal = a[index];
a[index] = element;
return oldVal;
}
};
}
Aucun commentaire:
Enregistrer un commentaire