简体   繁体   中英

JAVA ArrayList retrieve all objects from ArrayList method

I have an interface test class that implements another super-class. In the test class I have a method that is supposed to retrieve all objects in the ArrayList. First it checks to see if it is empty. If not, it should return the whole list. Here is what I have attempted.

public class ProductDBImpl implements ProductDB {

// field declarations
ArrayList<Product> products = new ArrayList<Product>();
@Override
public List<Product> getAllProducts() 
{
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    // create an iterator for the Arraylist

    if (products.isEmpty())
    {
        return new ArrayList<Product>() ;
    }
    return products;
}

Unfortunately, when I run my test script (tests the interface test class and super-class) the getAllProducts() method is not working the way it should and it is returning a productdb.util.AssertionFailedError: expected:<1> but was:<0> message. Here is the way the test script is testing the getAllProducts() method:

    // testing getAllProducts()
    List<Product> productList = productDB.getAllProducts();     
    int size = productList.size();      
    productList.remove(0);      
    productList = productDB.getAllProducts();       
    Assert.assertEquals(size, productList.size());

Please help me identify my error. Thanks.

You return a reference to the ArrayList object. Then you modify the object. Then you get another reference to it and discover that the object was modified.

If you want to protect the data structure from external modification, then return a new List or an UnmodifiableList:

@Override
public List<Product> getAllProducts() 
{
    return new ArrayList<>(products);
}

Or, to avoid extra memory allocation and copies (note that this will cause the call to .remove() in your test code to fail; the important part is whether you must allow callers to modify the list they receive or not):

@Override
public List<Product> getAllProducts() 
{
    return Collections.unmodifiableList(products);
}

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