Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

co-variance using Arrays.asList in java?

Tags:

java

types

list

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?

like image 706
Hongxu Chen Avatar asked Feb 10 '23 04:02

Hongxu Chen


2 Answers

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)

like image 128
Elliott Frisch Avatar answered Feb 11 '23 17:02

Elliott Frisch


You simply have to give it a generic hint:

List<NameValuePair> p = Arrays.<NameValuePair>asList(new BasicNameValuePair("c", coin), new BasicNameValuePair("mk_type", fromCoin));
like image 39
Brett Okken Avatar answered Feb 11 '23 19:02

Brett Okken