ArrayList.toArray如何返回指定类型的数组

Welkin-Hu 2005-10-09 11:28:50
如果不带参数使用ArrayList.toArray,只能返回Object[]。
我想要的是整形数组,如何实现呢。

JDK 1.5的帮助文档如下,我看了还是不知道如何用。
<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method.

Specified by:
toArray in interface Collection<E>
Parameters:
a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns:
an array containing the elements of this list.
Throws:
ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
NullPointerException - if the specified array is null.
...全文
2302 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
野马和云图 2005-10-10
  • 打赏
  • 举报
回复
楼上正解
Marcus-Z 2005-10-10
  • 打赏
  • 举报
回复 1
return (String[])dataList.toArray(String[list.size()]);
Roy_Sashulin 2005-10-10
  • 打赏
  • 举报
回复
楼主的这个问题有意思,所以引来了猩猩。我两个三角不好意思
我同意interhanchi(闭关修练中!) 的说法,因为在一个ArrayList中加入元素时,这个元素必须是一个object型的,不能是基本数据类型,如果要加入基础数据类型的元素,必须用到对应的类来转换,如int型必须用Integer类来转,Arraylist.add(new Integer(i))。相反,如果要返回list中的数据组,也要用Integer来转回。
superslash 2005-10-10
  • 打赏
  • 举报
回复
全是猩猩?看错了吧?
treeroot 2005-10-10
  • 打赏
  • 举报
回复
String[] strArr= new String[dataList.size()];
dataList.toArray(strArr);
sandyen 2005-10-10
  • 打赏
  • 举报
回复
如果你的List里面放置的是String的话。
String[] strArr= new String[10];
dataList.toArray(strArr);
这样的话就可以了。不用使用泛型
star_str 2005-10-10
  • 打赏
  • 举报
回复
强制转形就可以了
(int[])xxx.toArray();
Welkin-Hu 2005-10-10
  • 打赏
  • 举报
回复
那JDK的API文档中讲的这种形式有什么作用呢?
<T> T[] toArray(T[] a)
interhanchi 2005-10-09
  • 打赏
  • 举报
回复
^_^,肯定了,ArrayList里面就只能放Object,就算转成数组,里面也肯定是Object[].
先转成Object,然后再转成int.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧