import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.RandomAccess;
class Main {
public static void main
(String[] args
) { ImmutableList<Integer> list = ImmutableList.create(1, 42);
}
public static final class ImmutableList<E> extends AbstractList<E>
implements List<E>, RandomAccess {
private final transient E[] arrayOfElements;
/**
*
*/
private ImmutableList() {
super();
arrayOfElements = null;
}
/**
*
* Constructor with a single element
*
* @param <E>
* type of element
* @throws NullPointerException
*/
private ImmutableList(E element) {
super();
if (element == null)
int i = 0, length = 0;
length = (this.arrayOfElements == null ? 1
: this.arrayOfElements.length + 1);
@SuppressWarnings("unchecked")
E
[] tempArray
= (E
[]) new Object[length
];
if (this.arrayOfElements == null) {
tempArray[length - 1] = element;
} else {
for (i = 0; i < tempArray.length; i++) {
tempArray[0] = this.arrayOfElements[i];
}
tempArray[i] = element;
}
this.arrayOfElements = tempArray;
}
/**
*
* Constructor with an array elements
*
* @param element
* @throws NullPointerException
*/
@SafeVarargs
private ImmutableList(E... elements) {
super();
if (elements == null)
this.
arrayOfElements = Arrays.
copyOf(elements, elements.
length); }
public static <E> ImmutableList<E> create(E element) {
return new ImmutableList<E>(element);
}
public static <E> ImmutableList<E> create(E[] arrayofEl) {
return new ImmutableList<E>(arrayofEl);
}
@SafeVarargs
public static <E> ImmutableList<E> create(E elt, E... arrayOfEl) {
@SuppressWarnings("unchecked")
E
[] tempArray
= (E
[]) new Object[arrayOfEl.
length + 1]; tempArray[0] = elt;
for (int i = 1; i < tempArray.length; i++) {
tempArray[i] = arrayOfEl[i - 1];
}
return new ImmutableList<E>(tempArray);
}
public static <E> ImmutableList<E> create() {
return new ImmutableList<E>();
}
@Override
public E get(int index) {
return arrayOfElements[index];
}
@Override
public int size() {
return arrayOfElements.length;
}
}
}