1
  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 ?

1
  • Just curious, why are you trying to create the ArrayList, when the functionality already exist in Java. Commented May 27, 2020 at 11:17

1 Answer 1

2

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>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.