Why Java does not recognize my ArrayList in a situation with an overloaded constructor

I have two constructors, for example:

public XMessage(Information info, List<Object> results) {
    this.information = info;
    this.results = results;
}

public XMessage(Information info, Object result) {
    this(info, Collections.singletonList(result));
}

I create an XMessage object by passing an Information object and an ArrayList object. When I check the result, it is a singleton list that wraps an ArrayList element. Why doesn't Java use a more suitable constructor and what are my options to force it?

+3
source share
3 answers

The first constructor is called:

new XMessage(information, new ArrayList<Object>());

Calls the second constructor:

new XMessage(information, new ArrayList<String>());

ArrayList<String>()not considered as List<Object>, but ArrayList<Object>-. Consider the following constructor:

public XMessage(Information info, List<? extends Object> results)

like @LuiggiMendoza suggested below.

+11

, List<String> ( ) a List<Object>, , , List<String> .

, .

+1

I tried the answers above and thought they worked for me, but that turned out to be false. I went with this constructor and worked for me:

public XMessage(Information info, Object result) {
    this(info, result instanceof List ? (List<Object>) result : Collections.singletonList(result));
}
0
source

All Articles