Noah Choi
Noah Choi

Reputation: 31

How can I copy the list<E> into the current array list in java? ( Generic list)

  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

Answers (1)

Stephen C
Stephen C

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:

  1. It is a bad idea to give your class the same name as a commonly used class in the standard library (java.util.ArrayList)

  2. Your class doesn't implement java.util.List<E>. Should it?

  3. If you are implementing java.util.List<E> you could save a lot of implementation effort by extending java.util.AbstractList<E>.

Upvotes: 2

Related Questions