Quantcast
Channel: Initialization of an ArrayList in one line - Stack Overflow
Viewing all articles
Browse latest Browse all 37

Answer by user439407 for Initialization of an ArrayList in one line

$
0
0

(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<A> getAList() {    return Arrays.asList(new B());}

The above results in a compiler error, because List<B> (which is what is returned by Arrays.asList) is not a subclass of List<A>, even though you can add Objects of type B to a List<A> object. To get around this, you need to do something like:

new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))

This is probably the best way to go about doing this, especially if you need an unbounded list or need to use inheritance.


Viewing all articles
Browse latest Browse all 37

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>