0

I implemented ArrayList here

public class JsonList<T> extends ArrayList<T>{
//extended functions

}

When creating an ArrayList, you can do something List<?> arrayList = new ArrayList<>(alreadyCreatedList);

I want to be able to do this with my JsonList. But currently, JsonList only has the default constructor JsonList<>(). I tried copying the ArrayList constructor like this

public JsonList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // defend against c.toArray (incorrectly) not returning Object[]
            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

And when creating a JsonList instance I do

JsonList<?> jsonList = new JsonList<>(alreadyCreatedList);

However, the elements are not saved. It returns an empty array. In addition, I can no longer create an empty instance JsonList<?> jsonList = new JsonList<>();

Solution: I don't know why I didn't think of it but for those out there here it is

public JsonList(Collection<? extends E> c) {
    super(c); // <-- invoke the appropriate super constructor
}

super(c) is all you need.

1
  • ArrayList had elementdata, size, and EMPTY_ELEMENTDATA declared as variables in that class so I just simply redeclared them in my class. Commented Jan 31, 2018 at 2:10

1 Answer 1

1

Make the first line super(c); without that, the compiler will insert super() which won't invoke the one you want (taking the Collection<? extends E> c).

public JsonList(Collection<? extends E> c) {
    super(c); // <-- invoke the appropriate super constructor
    elementData = c.toArray();
    // ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this. But I'm getting errors on my instances declared like this JsonList<?> filteredList = new JsonList<>();
The error says JsonList(Collection<? extends E> c) cannot be applied to ()
@ReiBrown If you also want an empty constructor, then provide one. If you add a constructor, the compiler no longer inserts the default constructor.

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.