How does this skeletal implementation works
This program is from effective java 2nd edition book, I couldn't understand how the int[] is converted to an List. Can someone help me explaining this. package examples.Chapter4.Item18;
// Concrete implementation built atop skeletal implementation - Page 95
import java.util.*;
public class IntArrays {
static List<Integer> intArrayAsList(final int[] a) {
if (a == null)
throw new NullPointerException();
return new AbstractList<Integer>() {
public Integer get(int i) {
return a[i]; // Autoboxing (Item 5)
}
@Override
public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val; // Auto-unboxing
return oldVal; // Autoboxing
}
public int size() {
return a.length;
}
};
}
public static void main(String[] a开发者_如何学Gorgs) {
int[] a = new int[10];
for (int i = 0; i < a.length; i++)
a[i] = i;
List<Integer> list = intArrayAsList(a);
Collections.shuffle(list);
System.out.println(list);
}
}
The example is giving a way to quickly wrap an array of primitive ints into a LIst of Integers. Internally it's using autoboxing to convert between int and Integer. The technique may be useful becase there's no similar conversion between int[] and List.
The fundamental technique is to build an anonymous implementation of AbstractList.
public class IntArrays {
static List<Integer> intArrayAsList(final int[] a) {
if (a == null)
throw new NullPointerException();
return new AbstractList<Integer>() {
// code here
}
}
The trick there is that final int[] a is availble to the implementation methods.
After that we just need to provide implementation methods of the interface defined by AbstractList, that is the methods get(), set() and size().
So each of those is pretty obvious, making good use of autoboxing.
public Integer get(int i) {
return a[i]; // Autoboxing (Item 5)
}
public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val; // Auto-unboxing
return oldVal; // Autoboxing
}
public int size() {
return a.length;
}
精彩评论