I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList places = new ArrayList();
places.add(\
(Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList
method is fixed size, but that's not the only issue with it. It also doesn't handle inheritance very well. For instance, suppose you have the following:
class A{}
class B extends A{}
public List getAList(){
return Arrays.asList(new B());
}
The above results in a compiler error, because List
(which is what is returned by Arrays.asList) is not a subclass of List
, even though you can add Objects of type B to a List
object. To get around this, you need to do something like:
new ArrayList(Arrays.asList(b1, b2, b3))
This is probably the best way to go about doing this, esp. if you need an unbounded list or need to use inheritance.