英文:
Convert from List<List<? extends Object>> to List<List<SpecificType>>
问题
这是我的问题,我有一个名为listToSublists
的函数,我绝对希望它是通用的,所以我写了这个:
public static List<List<? extends Object>> listToSubLists(List<? extends Object> elements, int sublistsLength) {
....
}
我希望以这种方式调用该函数:
List<LigneMaj> datas = ...;
List<List<LigneMaj>> datasPaquets = BatchUtils.listToSubLists(datas, 100);
出现了编译错误,我正在努力理解为什么会出现以下错误:
Type mismatch: cannot convert from List<List<? extends Object>> to List<List<LigneMaj>>
请问有人可以解释我漏掉了什么吗?
英文:
There is my problem, I've a function listToSublists
I absolutely want to be generic so i've wrote this :
public static List<List<? extends Object>> listToSubLists(List<? extends Object> elements, int sublistsLength) {
....
}
And i want to call that function that way :
List<LigneMaj> datas = ...;
List<List<LigneMaj>> datasPaquets = BatchUtils.listToSubLists(datas, 100);
It appears that it is impossible to compile and I'm struggling to understand why i'm getting this error :
Type mismatch: cannot convert from List<List<? extends Object>> to List<List<LigneMaj>>
Could someone explain what I am missing please?
答案1
得分: 0
public static
if (!elements.isEmpty()) {
List<List
final int sublists = ((elements.size() - 1) / sublistsLength) + 1;
for (int i = 0; i < sublists; i++) {
result.add(new ArrayList<>());
}
for (int currentIndex = 0; currentIndex < elements.size(); currentIndex++) {
final T elem = elements.get(currentIndex);
result.get(currentIndex / sublistsLength).add(elem);
}
return result;
} else {
return Collections.emptyList();
}
}
英文:
public static <T> List<List<T>> listToSubLists(List<T> elements, int sublistsLength) {
if (!elements.isEmpty()) {
List<List<T>> result = new ArrayList<>();
final int sublists = ((elements.size() - 1) / sublistsLength) + 1;
for (int i = 0; i < sublists; i++) {
result.add(new ArrayList<>());
}
for (int currentIndex = 0; currentIndex < elements.size(); currentIndex++) {
final T elem = elements.get(currentIndex);
result.get(currentIndex / sublistsLength).add(elem);
}
return result;
} else {
return Collections.emptyList();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论