ArrayList toArray() 转换不允许您使用 lenth()? [英] ArrayList toArray() conversion doesn't let you use lenth()?
问题描述
import java.util.*;
class Ball{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
Object a[]= al.toArray();
for (int i=0; i<a.length; i++)
{
System.out.println("Contents are :"+ a[i]);
}
}}
所以我创建了一个 ArrayList 并向其中添加了几个元素.然后使用 toArray 方法并得到对象数组 a.但是,如果我使用 i
i
length()
是一个方法,那么 length
是什么?
So I created an ArrayList and added a couple of elements to it. Then used toArray method and got object array a. However if I use i<a.length()
instead of i<a.length
, I get an error. What I don't understand is that if length()
is a method, what is length
?
其次,为什么我不能使用 for 循环输出 ArrayList 元素?
Secondly why can't I output ArrayList elements using a for loop?
for (int i=0; i<al.length(); i++)
{
System.out.println("Contents are :"+ al[i]);
}
(在这里使用 al.length() 以及 al[i] 会报错)
(over here using al.length() as well as al[i] gives an error)
推荐答案
首先,数组有一个 length
字段,它是 final
和 int
类型.数组没有 length
方法.
First, arrays have a length
field which is final
and int
type. Arrays do not have a length
method.
这在 Java 语言规范中有说明.第 10 章数组.(强调我的):
10.2.数组变量
一旦创建了一个数组对象,它的长度就永远不会改变.要使数组变量引用不同长度的数组,必须为变量分配对不同数组的引用.
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
10.3.数组创建
数组创建表达式指定元素类型、嵌套数组的层数、以及至少一层嵌套的数组长度.数组的长度可用作 final
实例变量 length
.
An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final
instance variable length
.
要访问数组的元素,使用[index]
:
To access to the elements of an array, use [index]
:
System.out.println(a[index]);
二、ArrayList
没有 length
方法,但是 size
.
Second, ArrayList
doesn't have a length
method, but size
.
要通过 inde 访问 ArrayList
的元素,请使用 get
方法:
To access to the elements of an ArrayList
by inde, use the get
method:
System.out.println(al.get(index));
请注意,ArrayList
不是数组,它是一个使用数组作为容器来保存将要存储的元素的类并且如果需要容纳更多元素,它将添加、删除、搜索和创建一个新数组.
Note that an ArrayList
is not an array, it is a class that uses an array as container to hold the elements it will store and will add, remove, search and create a new array if it needs to hold more elements that it can.
要遍历一个数组或一个List
(由ArrayList
实现的接口)的所有元素,最好使用增强的for
循环:
To go through all the elements of an array or a List
(interface implemented by ArrayList
), it is better to use the enhanced for
loop:
for (Object o : a) {
System.out.println(o);
}
for (Object o : al) {
System.out.println(o);
}
这篇关于ArrayList toArray() 转换不允许您使用 lenth()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!