开发者

Cloning java ArrayList and preventing it from modifications

开发者 https://www.devze.com 2022-12-26 00:46 出处:网络
I have a data structure like a database Rowset, which has got Rows and Rows have Columns. I need to initialize a Columns with null values, current code is to loop thru each column for a row and initia

I have a data structure like a database Rowset, which has got Rows and Rows have Columns. I need to initialize a Columns with null values, current code is to loop thru each column for a row and initialize values to NULL. Which is very inefficient if you have 100s or rows and 10s of column.

So instead I am keeping a initialized ArrayList of columns are RowSet level, and then doing a clone of this Arraylist for individual rows, as I believe clone() is faster than looping thru each element.

row.columnsValues = rowsset.NullArrayList.clone()

Problem with this is NullArrayList can be accidentally modified after being cloned, thus sacrificing the integrity of ArrayList at RowSet level, to prevent I am doing 3 things

1) Delca开发者_StackOverflowring ArrayList as final 2) Any elements I insert are final or null 3) Methods thurough this arrayList are passed to other arrays are declared a final.

Sounds like a plan, do you see any holes ?


You can use Collections.unmodifiableList((List) originalList.clone())

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists.


Still you will be able to add new elements to the array.

Why not just use:

row.columnsValues = Collections.unmodifiableList( (ArrayList) rowsset.NullArrayList.clone())


Here is the class whose instance keeps common ArrayList, this list is shared but can not be changed outside this class. Elements within this list also need to protect themselves as a shallow copy is being returned.

public class ArrayListUnmodifiability {


private ArrayList myList;
public ArrayListUnmodifiability() {

    myList = new ArrayList(2);      
    MyObj obj = new MyObj("Cannot be changed");
    obj.setValue(1);
    myList.add(0, obj);
    myList.add(1, null);        
}


public ArrayList getList() {
    return  (ArrayList) myList.clone();
}


}

public class MyObj {

public MyObj(String name) {
    this.name = name; 
}

public String getName() {
    return name;
}

private final String name;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消