-1

I want an ArrayList in Java that is unchangeable. So you can't delete or add any Elements. So all work is done by the Constructor.

So far I have tried making the List final the following way

public static final List<Integer> = new ArrayList<>;

This didnt work as you could somehow still add Elements to it.

Next I searched online and found out that you could override all Methods like this:

public NoChangeArrayList<T> extends ArrayList<T> {
    @Override
    public boolean remove() {
        //do nothing...
    }
    //override all change methods
    (...)
}

This though doesnt seem like a good solution to me, as I need to put in a lot of Work for such a simple thing.

Is there an easy way to make an unchangeable ArrayList?

Samuel
  • 388
  • 5
  • 15
  • [`Collections.unmodifiableList(list)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Collections.html#unmodifiableList(java.util.List)) - this does not change the `ArrayList`, but returns a new list (or view, since it will reflect any changes made to original list) – user85421 Mar 11 '20 at 18:36

1 Answers1

0

There is a library that does all of this for you called Guava, I use it for almost every project since unfortunately Java doesn't support truly immutable Collections until after Java 8.

List<Integer> mutable = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

List<Integer> immutable = ImmutableList.copyOf(mutable);
Jason
  • 5,154
  • 2
  • 12
  • 22