1

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.

8
  • 2
    size() returns the number of elements in the list. Initializing it with a size only allocates space but does not put anything into the list. Commented Feb 12, 2016 at 18:58
  • So how am I supposed to initialize an ArrayList with N null elements? Commented Feb 12, 2016 at 18:59
  • 1
    @JohnStrife you will need to manually add null to the list N times. Commented Feb 12, 2016 at 19:01
  • @JohnStrife why not just using an array of type T instead of creating an array list? Commented Feb 12, 2016 at 19:03
  • 1
    @kucing_terbang arrays and generics like T don't really play well together. Commented Feb 12, 2016 at 19:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I swear there's like a dozen of these questions...we need a canonical one now.
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]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.