Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize List<E> in empty class constructor?

The following code obviously doesn't work because List<E> is abstract:

public class MyList {
    private List<E> list;

    public MyList() {
        this.list = new List<E>();
    }
}

How can I initialize MyList class with an empty constructor if I need the list variable to be a LinkedList or a ArrayList depending on my needs?

like image 226
rfgamaral Avatar asked Dec 08 '22 03:12

rfgamaral


2 Answers

I'm not sure whether this is what you're asking...

public class MyList {
    private List<E> list;

    public MyList() {
        if (myNeeds)
            this.list = new LinkedList<E>();
        else
            this.list = new ArrayList<E>();
    }
}
like image 175
Thomas Avatar answered Dec 29 '22 22:12

Thomas


There are better alternatives for what you are trying to achieve:

  • Create a base class (abstract?) and override it twice, once for ArrayList and one for LinkedList
  • Inject the appropriate list to your class (dependency injection)
like image 32
kgiannakakis Avatar answered Dec 29 '22 21:12

kgiannakakis