Protect ArrayList from write access

Consider the following class:

public class Cars extends Observable{

    private ArrayList<String> carList = new ArrayList<String>();

    public void addToCarList(String car){
        // ...
        hasChanged();
        notifyObservers();
    }

    public void removeFromCarList(String car){
        // ...
        hasChanged();
        notifyObservers();
    }

    public ArrayList<String> getCarList() {
        return carList;
    }    
}

As you can see, every time the carList is changed, I want to notify the Observers . If someone does getCarList().add(...); , this is circumvented.

How can I give read access to the carList (for iterating over it etc.) but prevent write access to it except for the special methods addToCarList and removeFromCarList ?

I thought about this:

public ArrayList<String> getCarList() {
    return (ArrayList<String>)carList.clone();
}

but someone using my class would, when adding something to the clone of carList , not be informed that that's not the way it's meant to be done.


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 .


First, always avoid using concrete class at the left side of assignment and as a return value of method. So, fix your class as

public class Cars extends Observable{

    private List<String> carList = new ArrayList<String>();
    ........................

   public List<String> getCarList() {
        return carList;
   }
}    

Now you can use Collections.unmodifiableList() to make you list read-only:

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

BTW, if you do not really have to return List you can probably return Collection or even Iterable . This will make increase the encapsulation level of your code and make future modifications easier.


Jon Skeet's answer is excellent (as always) but the one thing it doesn't touch on is concurrency issues.

Returning an unmodifiable collection will still leave you with issues if multiple threads are accessing this object at the same time. For example if one thread is iterating over the list of cars and then at the same time another thread adds a new card.

You will still need to synchronize access to that list somehow, and this is one reason why you might consider returning a clone() of the list as well as or instead of just wrapping it in the unmodifiableList wrapper. You would still need to synchronize around the clone() but once the clone is completed and the list returned to the querying code it no longer needs to be synchronized.

链接地址: http://www.djcxy.com/p/53928.html

上一篇: foreach如何调用GetEnumerator()? 通过IEnumerable引用或通过...?

下一篇: 保护ArrayList不受写入权限的限制