1

I am struggling with creating ImmutableList Unmodified will only restrict to the produced collection although the Collection from where it had been created can be modified.

public static void main(String[] args) {
        List<String> strings = new ArrayList<String>();
        // unmodifiable.add("New string");
        strings.add("Aha 1");
        strings.add("Aha 2");
        List<String> unmodifiable = Collections.unmodifiableList(strings);
        // Need some way to fix it so that Strings does not Modify
        strings.add("Aha 3");
        strings.add("Aha 4");

        for (String str : unmodifiable) {
            System.out.println("Reference Modified :::" + str);
        }

        List<List<String>> nCopies = Collections.nCopies(3, strings);
        for (List<String> innerString : nCopies) {
            innerString.add("Aha Inner");
        }

        for (List<String> innerString : nCopies) {

            for (String str : innerString) {
                System.out.println(str);
            }
        }

    }
Kumar Abhishek
  • 3,004
  • 33
  • 29
  • yes, StackOverflow has similar questions about Collections.unmodifiable, but I could not find answer stating a way to achieve this, and don't wanted to use any other API,So I posted this Question – Kumar Abhishek Mar 17 '16 at 12:14

2 Answers2

1

You will need to create a copy of the original list: the unmodifiableList is just a wrapper to the original.

You could use an ArrayList List<String> unmodifiable = Collections.unmodifiableList(new ArrayList<>(strings)), or guava List<String> unmodifiable = ImmutableList.copyOf(strings)

dfogni
  • 763
  • 9
  • 14
0

Try this.

public class MyList<E> extends AbstractList<E> {

    boolean modifiable = true;
    List<E> list = new ArrayList<>();

    @Override
    public E get(int index) {
        return list.get(index);
    }

    @Override
    public int size() {
        return list.size();
    }

    public boolean getModifialbe() {
        return modifiable;
    }

    public void setModifiable(boolean modifiable) {
        this.modifiable = modifiable;
    }

    @Override
    public boolean add(E e) {
        if (!modifiable)
            throw new UnsupportedOperationException("unmodifiable");
        return list.add(e);
    }

    @Override
    public String toString() {
        return list.toString();
    }
}

and

MyList<String> list = new MyList<>();
list.add("Aha 1");
list.add("Aha 2");
list.setModifiable(false);
list.add("Aha 3");  // UnsupportedOperationException!
  • yeah It helps, but does not achieves Immutability completely bcz i will end up overriding methods like addAll,Remove,set , which can be done by Say with new version of AbstractList coming if they add something new, My Program will fail. anything which is even more simple. – Kumar Abhishek Mar 17 '16 at 07:41