如何将List<List<String>>转换为List<List<Object>>?

huangapple go评论89阅读模式
英文:

How to convert List<List<String>> into List<List<Object>>?

问题

如何将List&lt;List&lt;String&gt;&gt;转换为List&lt;List&lt;Object&gt;&gt;?例如,getValue()返回List&lt;List&lt;String&gt;&gt;,然后我需要将这个列表传递给Adapter的构造函数,类型为List&lt;List&lt;Object&gt;&gt;。我不想将构造函数泛型化。我该怎么做?当我尝试进行类型转换时,会出现Inconvertible types错误。

new TableTimetableAdapter(Repo.getValue());
英文:

Like in convert how to convert List&lt;List&lt;String&gt;&gt; into List&lt;List&lt;Object&gt;&gt;? For example getValue() returns List&lt;List&lt;String&gt;&gt; and then I need to pass this List to Adapter's constructor as List&lt;List&lt;Object&gt;&gt;. I don't to generify this constuctor. How can I do that? When I try to cast I get Inconvertible types error

new TableTimetableAdapter(Repo.getValue());

答案1

得分: 3

Casting should actually work... You are not allowed to cast List&lt;List&lt;String&gt;&gt; to List&lt;List&lt;Object&gt;&gt; but you can just cast it to List like so:

new TableTimetableAdapter((List) Repo.getValue());
英文:

Casting should actually work... You are not allowed to cast List&lt;List&lt;String&gt;&gt; to List&lt;List&lt;Object&gt;&gt; but you can just cast it it to List like so:

new TableTimetableAdapter((List) Repo.getValue());

答案2

得分: 0

由于List&lt;List&lt;String&gt;&gt;List&lt;List&lt;Object&gt;&gt;更具体,您无需进行强制转换。

英文:

Since List&lt;List&lt;String&gt;&gt; is more specific than List&lt;List&lt;Object&gt;&gt; you do not need to cast.

答案3

得分: 0

我认为你不能只是将一个类型的列表强制转换为另一个类型,你需要将列表的内容映射到所需的子类型中。

你可以像这样做:

List<List<Object>> objects = Repo.getValue().stream()
        .map(strings -> strings.stream().map(string -> (Object) string).collect(Collectors.toUnmodifiableList()))
        .collect(Collectors.toUnmodifiableList());
英文:

I think you can't just cast a List of a type to another type, you would need to map the content of the lists into the desired sub-type.

You could do something like this:

List&lt;List&lt;Object&gt;&gt; objects = Repo.getValue().stream()
        .map(strings -&gt; strings.stream().map(string -&gt; (Object) string).collect(Collectors.toUnmodifiableList()))
        .collect(Collectors.toUnmodifiableList());

huangapple
  • 本文由 发表于 2020年8月7日 03:29:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63290536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定