How to initialize List <E> in an empty class constructor?
The following code obviously does not work, because List<E> is abstract:
public class MyList { private List<E> list; public MyList() { this.list = new List<E>(); } } How can I initialize the MyList class with an empty constructor if I need a list variable like LinkedList or ArrayList depending on my needs?
Why not use a protected (and possibly abstract ) method, for example:
public abstract class MyList<T> { protected final List<T> list; public MyList() { list = createList(); } public MyList(boolean preferLinked) { list = preferLinked? new LinkedList<T>() : new ArrayList<T>(); } // Allows client code which subclasses from MyList to override the // default behaviour protected List<T> createList() { return new ArrayList<T>(); } } A list is an interface and as such cannot be built. Only implementations of the specified interface can be built (for example, ArrayList). In addition, you need to know type (E) when building.
This should work:
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class MyList<E> { private List<E> list; public MyList(boolean linked) { if (linked) { list = new LinkedList<E>(); } else { list = new ArrayList<E>(); } } } As I understand it, you cannot use only an empty constructor, because you have a node solution in your model when you need to choose between a list type, so you will definitely need to tell the program which list will be. In my opinion this is the best solution:
public class MyList { private List<E> list; public MyList() { this.list = new LinkedList<E>(); } //an overload for another type, public MyList(bool INeedArray) { if (INeedArray) this.list = new ArrayList<E>(); } }