从List<List<? extends Object>>转换为List<List<SpecificType>>

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

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&lt;List&lt;? extends Object&gt;&gt; listToSubLists(List&lt;? extends Object&gt; elements, int sublistsLength) {
	....
}

And i want to call that function that way :

List&lt;LigneMaj&gt; datas = ...;
List&lt;List&lt;LigneMaj&gt;&gt; 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&lt;List&lt;? extends Object&gt;&gt; to List&lt;List&lt;LigneMaj&gt;&gt;

Could someone explain what I am missing please?

答案1

得分: 0

public static List<List> listToSubLists(List elements, int sublistsLength) {
if (!elements.isEmpty()) {
List<List> 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();
}

}

英文:
public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; listToSubLists(List&lt;T&gt; elements, int sublistsLength) {
        if (!elements.isEmpty()) {
            List&lt;List&lt;T&gt;&gt; result = new ArrayList&lt;&gt;();

            final int sublists = ((elements.size() - 1) / sublistsLength) + 1;
            for (int i = 0; i &lt; sublists; i++) {
                result.add(new ArrayList&lt;&gt;());
            }

            for (int currentIndex = 0; currentIndex &lt; elements.size(); currentIndex++) {
                final T elem = elements.get(currentIndex);
                result.get(currentIndex / sublistsLength).add(elem);
            }

            return result;
        } else {
            return Collections.emptyList();
        }
    }

huangapple
  • 本文由 发表于 2020年8月5日 18:05:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63262839.html
匿名

发表评论

匿名网友

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

确定