Reputation: 31
public class ArrayList<E> {
public static final int DEFAULT_CAPACITY = 10;
private int size; // number of occupied space
private E[] data; // ArrayList, encapsulate with the private keyword
public ArrayList() {
this(DEFAULT_CAPACITY);
size = 0;
}
@SuppressWarnings("unchecked")
public ArrayList(int capacity) {
data = (E[])new Object[capacity];
size = 0;
if(capacity < 0) {
throw new IllegalArgumentException("Capacity should more than 0");
}
}
//Need to be fixed
//
//
//
public ArrayList(List<E> other) {
List<E> newList = new ArrayList<E>();
}
}
This is my code, and I made a constructor with the parameter( List other), the last one. I try to copy the list into the current array list; the E[] data, variable. But the error is List cannot copy the data to the E[]. So, I'm a little bit confused. How can I copy them? if I cannot How can I copy the List ?
Upvotes: 1
Views: 52
Reputation: 719336
This should do it.
@SuppressWarnings("unchecked")
public ArrayList(List<E> other) {
data = (E[]) other.toArray();
size = data.length;
}
We are making use of the toArray()
method implemented by all List
types.
Alternatively allocate an array and copy the elements with a loop of the appropriate kind. (Avoid using get(i)
because it is O(N)
for some kinds of list.)
Notes:
It is a bad idea to give your class the same name as a commonly used class in the standard library (java.util.ArrayList
)
Your class doesn't implement java.util.List<E>
. Should it?
If you are implementing java.util.List<E>
you could save a lot of implementation effort by extending java.util.AbstractList<E>
.
Upvotes: 2