英文:
How to convert List<List<String>> into List<List<Object>>?
问题
如何将List<List<String>>转换为List<List<Object>>?例如,getValue()返回List<List<String>>,然后我需要将这个列表传递给Adapter的构造函数,类型为List<List<Object>>。我不想将构造函数泛型化。我该怎么做?当我尝试进行类型转换时,会出现Inconvertible types错误。
new TableTimetableAdapter(Repo.getValue());
英文:
Like in convert how to convert List<List<String>> into List<List<Object>>? For example getValue() returns List<List<String>> and then I need to pass this List to Adapter's constructor as List<List<Object>>. 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<List<String>> to List<List<Object>> 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<List<String>> to List<List<Object>> but you can just cast it it to List like so:
new TableTimetableAdapter((List) Repo.getValue());
答案2
得分: 0
由于List<List<String>>比List<List<Object>>更具体,您无需进行强制转换。
英文:
Since List<List<String>> is more specific than List<List<Object>> 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<List<Object>> objects = Repo.getValue().stream()
.map(strings -> strings.stream().map(string -> (Object) string).collect(Collectors.toUnmodifiableList()))
.collect(Collectors.toUnmodifiableList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论