I've implemented a class in Java which, internally, stores a List. I want the class to be immutable. However, I need to perform operations on the internal data which don't make sense in the context of the class. Hence, I have another class which defines a set of algorithms. Here is a simplified example:
Wrapper.java
import java.util.List;
import java.util.Iterator;
public class Wrapper implements Iterable<Double>
{
private final List<Double> list;
public Wrapper(List<Double> list)
{
this.list = list;
}
public Iterator<Double> iterator()
{
return getList().iterator();
}
public List<Double> data() { return getList(); }
}
Algorithm.java
import java.util.Iterator;
import java.util.Collection;
public class Algorithm
{
public static double sum(Collection<Double> collection)
{
double sum = 0.0;
Iterator<Double> iterator = collection.iterator();
// Throws NoSuchElementException if the Collection contains no elements
do
{
sum += iterator.next();
}
while(iterator.hasNext());
return sum;
}
}
Now, my question is, is there a reliable way to prevent someone from modifying my internal data despite the fact that my class is meant to be immutable? While I have provided a data() method for read-only purposes, there is nothing to stop someone from modifying the data via methods such as clear() and remove(). Now, I realize that I could provide access to my data exclusively via iterators. However, I have been told that it is typical to pass a Collection. Secondly, if I had an algorithm that required more than one pass over the data, I would have to provide multiple iterators, which seems like a slippery slope.
Okay, hopefully there is a simple solution that will resolve my concerns. I am just getting back into Java, and never considered these things before dealing with const in C++. Thanks in advance!
Oh! There's one more thing I just thought of. I can't practically return a copy of the internal List. The List will typically contain hundreds of thousands of elements.