Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java recognize my ArrayList in an overloaded constructor situation

I have two constructors setup like so:

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 the XMessage object by passing in an Information object and an ArrayList object. When I inspect the result, it is a singleton list wrapping the ArrayList item. Why doesn't Java use the more appropriate constructor and what are my options to force it?

like image 654
MikeG Avatar asked Mar 28 '26 19:03

MikeG


1 Answers

Calls first constructor:

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

Calls second constructor:

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

ArrayList<String>() is not treated as List<Object> while ArrayList<Object> is. Consider using the following constructor:

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

as @LuiggiMendoza suggested below.

like image 79
Tomasz Nurkiewicz Avatar answered Mar 31 '26 05:03

Tomasz Nurkiewicz