将嵌套的List<List<T>>转换为嵌套的ArrayList<ArrayList<T>>。

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

Cast nested List<List<T>> to nested ArrayList<ArrayList<T>>

问题

什么是将 List<List<T>> 强制转换为 ArrayList<ArrayList<T>> 的最佳/性能最佳的方法?

假设我有一个名为 IFoo.getListOfLists() 的接口,它将给我 List<List<T>>。同时假设我知道这些 List<List<T>> 实际上是 ArrayList<ArrayList<T>> 的实例。

一个简单的解决方案是:

ArrayList<ArrayList<T>> result = new ArrayList<>();
for (List<T> arrayList : IFoo.getListOfLists()) {
    result.add((ArrayList<T>)arrayList);
}

但是是否有更好的方法呢?尤其是因为我已经知道这些实例实际上是 ArrayList

英文:

What's the best / most performant way to cast a List&lt;List&lt;T&gt;&gt; to ArrayList&lt;ArrayList&lt;T&gt;&gt;?

Let's assume I have an interface IFoo.getListOfLists() which will give me the List&lt;List&lt;T&gt;&gt;. Let's also assume I know that these List&lt;List&lt;T&gt;&gt; are in fact instances of ArrayList&lt;ArrayList&lt;T&gt;&gt;.

One simple solution would be:

    ArrayList&lt;ArrayList&lt;T&gt;&gt; result = new ArrayList&lt;&gt;();
	for (List&lt;T&gt; arrayList : IFoo.getListOfLists()) {
		result.add((ArrayList&lt;T&gt;)arrayList);
	}

but is there a better approach? Especially, because I already know that the instances are in fact ArrayLists.

答案1

得分: 1

由于在运行时缺少对List的类型信息,您可以简单地将其转换为ArrayList

import java.util.ArrayList;
import java.util.List;

public class CastListList {

    public static void main(final String[] args) {
        final List<List<String>> strings = new ArrayList<>();
        strings.add(new ArrayList<>());
        strings.get(0).add("Hello World!");

        final ArrayList<ArrayList<String>> arrayList = cast(strings);
        System.out.println(arrayList.get(0).get(0));
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static <T> ArrayList<ArrayList<T>> cast(final List<List<T>> list) {
        return (ArrayList) list;
    }
}
英文:

since the type information for the List is absent at runtime, you can simply cast to ArrayList:

import java.util.ArrayList;
import java.util.List;

public class CastListList {

    public static void main(final String[] args) {
        final List&lt;List&lt;String&gt;&gt; strings = new ArrayList&lt;&gt;();
        strings.add(new ArrayList&lt;&gt;());
        strings.get(0).add(&quot;Hello World!&quot;);

        final ArrayList&lt;ArrayList&lt;String&gt;&gt; arrayList = cast(strings);
        System.out.println(arrayList.get(0).get(0));
    }

    @SuppressWarnings({ &quot;unchecked&quot;, &quot;rawtypes&quot; })
    private static &lt;T&gt; ArrayList&lt;ArrayList&lt;T&gt;&gt; cast(final List&lt;List&lt;T&gt;&gt; list) {
        return (ArrayList) list;
    }
}

huangapple
  • 本文由 发表于 2020年10月21日 19:22:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64462481.html
匿名

发表评论

匿名网友

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

确定