Co-variance using Arrays.asList in java?

When I create the list, I hope to initialize it with impatience; therefore I used Arrays.asList. However, it does not appear to be covariant with respect to inheritance.

For instance,

List<NameValuePair> p = Arrays.asList(new BasicNameValuePair("c", coin), new BasicNameValuePair("mk_type", fromCoin));

does not work ( BasicNameValuePairis a derived class NameValuePair).

So far, it's normal 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 a type List<NameValuePair>as an argument, I have to define pairsthis way. Is there any way to handle this issue elegantly?

+4
source share
2 answers

, , 1 Arrays.asList,

List<NameValuePair> p = Arrays.<NameValuePair>asList(new BasicNameValuePair(
        "c", coin), new BasicNameValuePair("mk_type", fromCoin));

1 ( Java)

+5

:

List<NameValuePair> p = Arrays.<NameValuePair>asList(new BasicNameValuePair("c", coin), new BasicNameValuePair("mk_type", fromCoin));
+3

All Articles