Immutable Objects in Java and Data Access

I implemented a class in Java that internally stores a list. I want the class to be immutable. However, I need to perform operations on internal data that does not make sense in the context of the class. Therefore, I have another class that 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;
    }
}

, , , , ? data() , - , clear() remove(). , . , , . -, , , , .

, , , . Java , const ++. !

! , . . .

+5
4

Collections.unmodifiableList .

public List<Double> data() { return Collections.unmodifiableList(getList()); }

javadoc:

. " " . "" , , , UnsupportedOperationException.

+23

Java . , , , , - .

, . , .

- , .

- , , - ( , , . Apache- ). , ( Collections).

, , - , . , IMyX IMyImmutableX. "" , .

. http://java.sun.com/docs/books/tutorial/essential/concurrency/imstrat.html

+5

Collections.unmodifiableList?

() List. , remove add, UnsupportedOperationException.

, , , . , .

, List, unmodifiableList, :

class MyValue {
    public int value;

    public MyValue(int i) { value = i; }

    public String toString() {
        return Integer.toString(value);
    }
}

List<MyValue> l = new ArrayList<MyValue>();
l.add(new MyValue(10));
l.add(new MyValue(42));
System.out.println(l);

List<MyValue> ul = Collections.unmodifiableList(l);
ul.get(0).value = 33;
System.out.println(l);

:

[10, 42]
[33, 42]

, , List, , , .

+5

, . , " Java".

, list , Collections.unmodifiableList . , , , .

, , , .

, . final. .

public final class Wrapper implements Iterable<Double> {
    private final List<Double> list;

    private Wrapper(List<Double> list) {
        this.list = Collections.unmodifiableList(new ArrayList<Double>(list));
    }

    public static Wrapper of(List<Double> list) {
         return new Wrapper(list);
    }

    public Iterator<Double> iterator() {
        return list.iterator();
    }

    public List<Double> data() {
        return list;
    }
}

Java.

+5
source

All Articles