简体   繁体   中英

ArrayList won't Add more than one Item

My Array will not add anything to the list after the first and keeps returning null when i search for anything after.

Is there something wrong with this method?

public void addItem(Item newItem) throws DuplicateItemException {
    Item tempItem;

    if(itemList == null) 
        itemList.add(newItem);

    try {
        tempItem = findItem(newItem.ID);

        if(tempItem == null) {
            itemList.add(newItem);
        }
        else {
            throw new DuplicateItemException(newItem.ID + "already exists");
        }
    } 
    catch (ItemNotFoundException e) {
        itemList.add(newItem);
    }
}

In your code:

if(itemList == null) 
    itemList.add(newItem);

if itemList is indeed null , how can you add to it?

Use this instead

if(itemList == null) {
    itemList = new ArrayList<>();
    itemList.add(newItem);
}

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