I have the following static factory method that creates a list view out of an int array:
public class ListFactory {
public static List<Integer> newInstance(final int[] numbers) {
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return numbers[index];
}
@Override
public int size() {
return numbers.length;
}
};
}
}
In “Effective Java”, Joshua Bloch mentioned this as an
Adapter that allows an int array to be viewed as a list of Integer instances
However, I remember that Adapter pattern uses composition and the instance of the anonymous list implementation should therefore use the int[]
as a member field. To verify the hypothesis and understand how the class is understood by the compiler, one can use the following command:
> javac -d . -XD-printflat ListFactory.java
From the output, one can clearly understand how the final parameter is passed to the inner anonymous class implementation:
public class ListFactory {
public ListFactory() {
super();
}
public static List newInstance(final int[] numbers) {
return new ListFactory$1(numbers);
}
}
class ListFactory$1 extends AbstractList {
/*synthetic*/ final int[] val$numbers;
ListFactory$1(/*synthetic*/ final int[] val$numbers) {
this.val$numbers = val$numbers;
super();
}
@Override()
public Integer get(int index) {
return Integer.valueOf(val$numbers[index]);
}
@Override()
public int size() {
return val$numbers.length;
}
@Override()
/*synthetic*/ public Object get(/*synthetic*/ int index) {
return this.get(index);
}
}