有谁能解释清楚这个初级问题,给分50

bpfrom 2002-03-22 11:59:09
Vector cars=new Vector;
(Car[]) cars.toArray(new Car[0]);
中new Car[0]怎么回事,参数0表示什么意思,再有toArray这样带参数是什么意思,查过帮助,没有弄明白.
...全文
40 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
coinicon 2002-03-22
  • 打赏
  • 举报
回复
new Car[0]
新建一个数组,数组中每个元素类型为Car

参数0
表示将新建的数组长度初始化为一个元素。
coinicon 2002-03-22
  • 打赏
  • 举报
回复
你的问题好像问过来吧?

Vector.toArray();
将Vector对象所有元素转换为一个数组输出。

Vector.toArray(Object []);
将Vector对象中所有元素转换为一个数组输出,数组的类型就是参数数组的类型。如果Vector对象中元素类型与参数数组的类型一致,就直接输出;如果Vector对象中元素类型与参数数组的类型<B>不一致</B>,就参照参数数组的类型新建一个数组输出,此新建数组类型与参数数组的类型一致,大小就是Vector的元素个数。

后一种形式的解释原文如下:Returns an array containing all of the elements in this Vector in the correct order. The runtime type of the returned array is that of the specified array. If the Vector fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this Vector.

结论:
(Car[]) cars.toArray();
如果原来cars对象中元素类型不是Car,则在强制转换时会导致类型不匹配的错误。

(Car[]) cars.toArray(new Car[0]);
确保cars对象转换出来的数组就是Car类型,在转换时<B>不会</B>导致类型不匹配的错误。
skyyoung 2002-03-22
  • 打赏
  • 举报
回复
Vector cars = new Vector();
cars.add(Car1);
cars.add(Car2);
Car[] car = cars.toArray(new Car[cars.size()]);

System.out.println(car.length); //2
bpfrom 2002-03-22
  • 打赏
  • 举报
回复
如果是二维数组该怎么声明呢?看看各位是不是真正理解了new Car[0]
wes109 2002-03-22
  • 打赏
  • 举报
回复
关注一下!
zjp009 2002-03-22
  • 打赏
  • 举报
回复
OK
pengji 2002-03-22
  • 打赏
  • 举报
回复
该说的都说了,应该很清楚了!
memphis0815 2002-03-22
  • 打赏
  • 举报
回复
>Vector cars=new Vector;
>(Car[]) cars.toArray(new Car[0]);
由于cars中并没有元素当然是0了
bpfrom 2002-03-22
  • 打赏
  • 举报
回复
参数0
表示将新建的数组长度初始化为一个元素。???????????????

不会吧,如果
(Car[]) cars.toArray(new Car[1]);
那参数又作何解释??
  • 打赏
  • 举报
回复
up

23,407

社区成员

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

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