我正在研究一个泛型类,它必须将T类型值存储在私有ArrayList
中,并且具有通常的get,set方法,但是当我初始化ArrayList
时,它只是保持大小0!我明确地使用带有int参数的构造函数,但它只保留0.这是我的构造函数和get方法(该类被称为GenericVector<T>
):
public GenericVector(int n)
{
vector = new ArrayList<>(n);
}
public T get (int pos)
{
if (pos >= vector.size())
{
System.out.println("UR DOIN WRONG");
System.out.println("Size is" + vector.size());
return null;
}
return vector.get(pos);
}
这是我的主要内容:
public static void main(String[] args)
{
GenericVector<String> vec = new GenericVector<String>(5);
vec.set(0, "EEE");
System.out.println("" + vec.get(0));
}
它只是打印:
UR DOIN WRONG
Size is 0
null
我真的不明白为什么用new ArrayList<>(n)
初始化矢量不起作用。
答案 0 :(得分:4)
ArrayList(int)
构造函数初始化data
的容量,而不是它的大小。如果要将新元素添加到数组列表,则应使用add(T)
或add(int, T)
方法。
答案 1 :(得分:0)
The ArrayList(int n) constructor creates ArrayList
with size 0 (no elements) and capacity n
. Documentation about capacity says:
Each ArrayList instance has a capacity. The capacity is the size of
the array used to store the elements in the list. It is always at
least as large as the list size. As elements are added to an
ArrayList, its capacity grows automatically. The details of the growth
policy are not specified beyond the fact that adding an element has
constant amortized time cost. [..] This may reduce the amount of
incremental reallocation.
If you want to have oneliner that creates ArrayList filled with nulls you can write:
ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[10]));