Reputation: 16615
In JDK 1.7, there is an ArrayList
declaration which is used by asList
.
Why did they make a new private static class
and not use java.util.ArrayList
:
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return a.clone();
}
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public E get(int index) {
return a[index];
}
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
}
Upvotes: 25
Views: 1189
Reputation: 1
if you use ArrayList, fast retrieve data from Table because it's index based, where we want fast retriving data we can use Arraylist ....
But ArrayList is not faster in the time of deleting record because rearranging the index is more complex
Where we want more deleting record we can use LinkedList it's not index based
ArrayList Declaration
java.util.List
ArrayList arrayList = new ArrayList();
Upvotes: -1
Reputation: 20376
The asList(T... a)
methods is declared to return a fixed-size list backed by the specified array which should also be serializable and implements RandomAccess
java.util.ArrayList
does not qualify for this definition (fixed size), so another type of java.util.List
should be used.
Upvotes: 2
Reputation: 4086
Because they're providing a List wrapper around the provided array which is O(1), rather than building an ArrayList from the elements in the array, which is O(n).
Is this causing you a problem? If so, it's probably because you're declaring your variables as ArrayList when you should be using List
Upvotes: 3
Reputation: 16364
Because the List
returned by Arrays.asList()
is backed by the given array. It wraps that array; changes to the array are reflected in the List
and vice versa.
Also, as a result of this, the List
returned here has a fixed size. So, it can't be an ArrayList
because ArrayList
can grow or shrink.
Upvotes: 27