英文:
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<List<T>>
to ArrayList<ArrayList<T>>
?
Let's assume I have an interface IFoo.getListOfLists()
which will give me the List<List<T>>
. Let's also assume I know that these List<List<T>>
are in fact instances of ArrayList<ArrayList<T>>
.
One simple solution would be:
ArrayList<ArrayList<T>> result = new ArrayList<>();
for (List<T> arrayList : IFoo.getListOfLists()) {
result.add((ArrayList<T>)arrayList);
}
but is there a better approach? Especially, because I already know that the instances are in fact ArrayList
s.
答案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<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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论