When I create a list, I hope to initialize it eagerly; so I used Arrays.asList
. However it seems that it is not covariant as to inheritance.
For example,
List<NameValuePair> p = Arrays.asList(new BasicNameValuePair("c", coin), new BasicNameValuePair("mk_type", fromCoin));
doesn't work (BasicNameValuePair
is a derived class of NameValuePair
).
While it OK to use add
as usual.
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("c", coin));
pairs.add(new BasicNameValuePair("mk_type", fromCoin));
Since the library API only accepts List<NameValuePair>
type as its argument, I have to define pairs
this way. Is there any way to deal with this issue elegantly?
If I understand your question, then I believe you could use an explicit1 generic type in the method call to Arrays.asList
like
List<NameValuePair> p = Arrays.<NameValuePair>asList(new BasicNameValuePair(
"c", coin), new BasicNameValuePair("mk_type", fromCoin));
1Generic Methods (The Java Tutorials)
You simply have to give it a generic hint:
List<NameValuePair> p = Arrays.<NameValuePair>asList(new BasicNameValuePair("c", coin), new BasicNameValuePair("mk_type", fromCoin));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With