P
P
parkito2016-11-16 01:10:39
Java
parkito, 2016-11-16 01:10:39

How to prevent array data from being modified through a getter?

Hello. Help, please, to solve a problem. Given the code in which the array is changed through the getter. What are the ways to prevent such a change through a getter?

class two {
    private final List<Integer> array = new ArrayList();

    public final List<Integer> getArray() {
        return array;
    }


    @Override
    public String toString() {
        return "two{" +
                "array=" + array +
                '}';
    }
}

public class one {
    public static void main(String[] args) {
        two tw = new two();
        System.out.println(tw);
        tw.getArray().add(1);
        tw.getArray().add(2);
        tw.getArray().add(3);
        System.out.println(tw);

    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2016-11-24
@ZzeroCool

It seems to me that in your case you need to look towards the Singleton pattern. For the return of the created copy, in my opinion, is still a crutch.

A
Avrelio, 2020-11-06
@Avrelio

Collections.unmodifiableList(List);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question