Protect ArrayList from write access

You can return an unmodifiable view of it, changing the return type to List<String> instead of ArrayList<String>:

public List<String> getCars() {
    return Collections.unmodifiableList(carList);
}

Note that as Collections.unmodifiableList does only provide a view, the caller will still see any other changes that are made via addToCarList and removeFromCarList (which I’d rename to addCar and removeCar, probably). Is that what you want?

Any mutating operations on the returned view will result in an UnsupportedOperationException.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)