import java.util.ArrayList; /** * When Java cannot be sure that operations are legal within * a subroutine it will sometimes take refuge in immutability * That is, it will let you read, but not write. Note that * programmer can declare immutability using final tag. */ public class Immut { /** * The array list is mutable * @param mut */ public void mutable(ArrayList mut) { mut.add(14); mut.remove(0); } /** * The ArrList is immutable because of the final tag. * @param mut */ public void immutF(final ArrayList mut) { mut.add("in mutable"); mut.remove(0); } /** * The arrayList is immutable because you do not know the type of * its contents (at all). * @param imm */ public void immut(ArrayList imm) { System.out.println(imm.size()); System.out.println(imm.get(0)); // imm.add(3); //Adding not allowed // Number n = imm.get(0); // Not allowed, you do not know it is a number imm.remove(0); } public void immutN(ArrayList imm) { System.out.println(imm.size()); System.out.println(imm.get(0)); imm.add(3); //Adding not allowed you still do not know the // underlying type Number n = imm.get(0); // Allowed!! imm.remove(0); } public void test() { ArrayList as = new ArrayList(); as.add(4); as.add(5); System.out.println(as); mutable(as); System.out.println(as); } public static void main(String[] args) { new Immut().test(); } }