My question is regarding declaring an arraylist as final. I know that once I write final ArrayList list = new ArrayList();
I can add, delete objects from this list,
You're right that declaring the list
final means that you cannot reassign the list
variable to another object.
The other question (I think) was
public class SomeClass {
private static final ArrayList list = new ArrayList();
}
vs
public class SomeClass {
ArrayList list = new ArrayList();
}
let's take each modifier in turn.
private
Means only this class (SomeClass
) can access list
static
Means that there is only one instance of the list
variable for all instances of SomeClass
to share. The list instance is associated with the SomeClass class rather than each new SomeClass instance. If a variable is non-static it's said to be an instance variable
final
as you know means that you cannot reassign the list variable another value.
In the second declaration there are no modifiers, so the variable is an instance variable and it also gets package-private access protection (Sometimes called default access protection). This means that this class (SomeClass
) and other classes in the same package can access the variable.
You can find out more about public
, private
, and package-private
here: Access control
You can find out more about final
and static
here: Class variables