user5460725
user5460725

Reputation:

ArrayList doesn't... initialize?

I was working on a generic class, which had to store T type values in a private ArrayList and have the usual get, set methods, but when I initialize the ArrayList it just stays to size 0! I explicitly use the constructor with int argument, but it just stays 0. Here's my constructor and get method (the class is called 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);
}

And here's my main:

public static void main(String[] args)
{
    GenericVector<String> vec = new GenericVector<String>(5);
    vec.set(0, "EEE");
    System.out.println("" + vec.get(0));
}

It just prints:

UR DOIN WRONG
Size is 0
null

I don't really get why initializing the vector with new ArrayList<>(n) doesn't work.

Upvotes: 1

Views: 870

Answers (2)

Paweł Adamski
Paweł Adamski

Reputation: 3415

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]));

Upvotes: 0

Mureinik
Mureinik

Reputation: 311338

The ArrayList(int) constructor initializes the ArrayList's capacity, not it's size. If you want to add a new element to an array list, you should use the add(T) or add(int, T) method.

Upvotes: 4

Related Questions