How to initialize List<E> in empty class constructor?
The following cod开发者_JAVA技巧e 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?
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>();
}
}
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)
Why not use a protected (and possibly abstract
method) like:
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>();
}
}
boolean shouldThisBeAnArrayList=true; // Set to false to use LinkedList
if(shouldThisBeAnArrayList) {
this.list = new ArrayList<E>();
}
else {
this.list=new LinkedList<E>();
}
You need to determine what "your needs" are in the default case - LinkedList or ArrayList. If you can't - say, if the need changes depending on something that happens over the object's lifetime, then the list needs to change, too.
List is an interface and as such, cannot be constructed. Only implementations of said interface can be constructed (e.g. ArrayList). Also, you need to know the type (E) at construction.
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>();
}
}
}
I would think you could do the following:
public class MyList<T> {
private List<T> list;
public MyList() {
this.list = new ArrayList<T>();
}
}
As I understand, you cannot use just a empty constructor, because you have a decision node in your model, when you need to choose between the type of the list, so, you will have to tell the program any way what kind of list will be. This seems to be the best solution in my opinion:
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>();
}
}
public class MyList<T> {
private List<T> list = new ArrayList<T>();
}
This is what I use in classes.. I have for a long initialized what I could when defining the private variable it self.
精彩评论