使arrayList.toArray()返回特定类型 [英] make arrayList.toArray() return more specific types

查看:140
本文介绍了使arrayList.toArray()返回特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,一般 ArrayList.toArray()将返回一个类型的对象[] ....但本来这是一个
的ArrayList 对象的自定义,我怎么做的toArray()返回一个类型的自定义[] ,而不是对象[]

So, normally ArrayList.toArray() would return a type of Object[]....but supposed it's an Arraylist of object Custom, how do I make toArray() to return a type of Custom[] rather than Object[]?

推荐答案

这样的:

List<String> list = new ArrayList<String>();

String[] a = list.toArray(new String[list.size()]);

人们很容易做到这一点,如:

It's tempting to do it like:

String[] a = list.toArray(new String[0]);

但内部的实施将反正realloc的一个适当大小的数组,以便你更好地做前期。

but the internal implementation will realloc a properly sized array anyway so you are better doing it upfront.

如果您的列表没有正确输入你需要的toArray调用之前做一个演员。像这样的:

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);

这篇关于使arrayList.toArray()返回特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆