tags:

views:

225

answers:

4

To create a List, why doesn't Java allow them to be created then elements added one by one?

This works:

public static List<TrackedItem> create(List<Item> items)
{
    TrackedItem[] arr = new TrackedItem[items.size()];

    int i = 0;
    for (Item item : items)
    {
        arr[i] = TrackedItem.createOrUpdate(item);

        i++;
    }

    return java.util.Arrays.asList(arr);
}

This does not work (tracked.add() causes a NullPointerException):

public static List<TrackedItem> create(List<Item> items)
{
    List<TrackedItem> tracked = java.util.Collections.emptyList();

    for (Item item : items)
    {
        tracked.add(TrackedItem.createOrUpdate(item));
    }

    return tracked;
}
+15  A: 

java.util.Collections.emptyList();

static List emptyList() Returns the empty list (immutable).

That means, you will not be able to change this list.

Its defined:

static List EMPTY_LIST The empty list (immutable).

Quotes from Java sun reference

Edit:

To create a new list you could use e.g.

List myList = new ArrayList<MyClass>();
InsertNickHere
+1: The problem here is in attempting to modify the value returned from `Collections.emptyList()`, nothing to do with generic parameters.
Andrzej Doyle
+4  A: 

Use the following syntax:

public static List<TrackedItem> create(List<Item> items)
{
    List<TrackedItem> tracked = new ArrayList<TrackedItem>();

    for (Item item : items)
    {
        tracked.add(TrackedItem.createOrUpdate(item));
    }

    return tracked;
}
Marc van Kempen
NB You need to instantiate a list of a specific type (in this case ArrayList, could also have been LinkedList, etc.) to which you can add your items.
Marc van Kempen
+2  A: 

This might be a misunderstanding.

Even if it is called emptyList, it isn't a list which is just empty and ready to be populated. This emptyList is designed to be empty at all times. You can't add to this special list.

To get a 'usable' empty list you can either

List<String> list = new ArrayList<String>();  // create a new one or
list.add("if you have an list");
list.clear();                                 // just clear it
Andreas_D
A: 

create a new arrayList by :

List<T> tracked = new ArrayList<T>();

List is only an interface ... you can't make a new one. you only can implement it.

Saher