Вопрос по java – в чем смысл окончательного ArrayList?

60

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded Pankaj Kumar

Ваш Ответ

12   ответов
0

14

final List<String> list = new ArrayList<String>();

list = new LinkedList<String>();
     ^
     Compiler error here

Collections.unmodifiableList()

0

Error: User Rate Limit Exceeded

The final arrayList can still be modified, refer to the example below and run it to see for your self.

Here is the immutable class with immutable List declaration:

public final class ImmutableClassWithArrayList {
 final List<String> theFinalListVar = new ArrayList<String>();
}

And here is the driver:

public class ImmutableClassWithArrayListTester {
public static void main(String[] args) {
    ImmutableClassWithArrayList immClass = new ImmutableClassWithArrayList();
    immClass.theFinalListVar.add("name");
    immClass.theFinalListVar.forEach(str -> System.out.println(str));
 }
}

As you can see, the main method is adding (modifying) the list. So the only thing to note is that the "reference" to the object of the collection type can't be re-assigned to another such object. As in the answer by adarshr above, you can't do immClass.theFinalListVar = new ArrayList(); in the main method here.

Error: User Rate Limit Exceeded

3

It prevents the variable from being changed if it is expected to stay constant. This can help prevent future bugs. Making variables final can help the compiler make certain performance optimisations.

8

Error: User Rate Limit Exceedednew ArrayListError: User Rate Limit Exceeded

1

Error: User Rate Limit Exceeded

 package com.home.immutable.serial;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public final class ImmutableBySerial {

    private final int num;
    private final String str;
    private final ArrayList<TestObjSerial> immutableList;

    ImmutableBySerial(int num, String str, ArrayList<TestObjSerial> list){
        this.num = num;
        this.str = str;
        this.immutableList = getDeepCloned(list);
    }

    public int getNum(){
        return num;
    }

    public String getStr(){
        return str;
    }

    public ArrayList<TestObjSerial> getImmutableList(){
        return getDeepCloned(immutableList);
    }

    private ArrayList<TestObjSerial> getDeepCloned(ArrayList<TestObjSerial> list){
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        ArrayList<TestObjSerial> clonedObj = null;
        try {
             fos = new FileOutputStream(new File("temp"));
             oos = new ObjectOutputStream(fos);
             oos.writeObject(list);
             fis = new FileInputStream(new File("temp"));
             ois = new ObjectInputStream(fis);
             clonedObj = (ArrayList<TestObjSerial>)ois.readObject();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return clonedObj;
    }
}
5

finalError: User Rate Limit Exceeded

JMM clearly defines a final field's initialization completion is guaranteed.

Error: User Rate Limit Exceeded

Compilers are free to reorder them across memory barriers. Compilers can always read a cached copy.
1

1

Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.

119

Error: User Rate Limit Exceededcollection instance:

final List<Integer> list = new ArrayList<Integer>();
list = new ArrayList<Integer>(); // Since `list' is final, this won't compile

Error: User Rate Limit Exceededfinal.

I still can add to ArrayList new elements, remove elements and update it.

Error: User Rate Limit ExceededCollections.unmodifiableList():

final List<Integer> list = Collections.unmodifiableList(new ArrayList<Integer>(...));
Error: User Rate Limit Exceeded
5

final

final

final List fixedList = Collections.unmodifiableList(someList);

fixedListsomeList

1

final

Похожие вопросы