简体   繁体   中英

Why doesn't Java allow “new List<T>”?

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;
}

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 eg

List myList = new ArrayList<MyClass>();

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;
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM