This wasn’t a revelation or anything. My AP Computer Science class was wondering what would happen if one were to set an ArrayList to final. Remember, when you add the final prefix to an variable declaration, it becomes constant and therefore not changeable. (That definition is where we got lost.)
I wrote some sample code that you can test out on your own. I came to my conclusions based on this same code too.
import java.util.*;
public class FinalArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
final ArrayList<String> list2 = new ArrayList<String>();
list.add("hello");
list.add("world");
list2.add("hello");
list2.add("world");
for (String item : list) {
System.out.println("From variable ArrayList - " + item);
}
System.out.println("");
for (String item : list2) {
System.out.println("From final ArrayList - " + item);
}
}
}
Definition of Final
I looked up the true definition of final. I came to the same understanding after making my example above. I’ll explain why it makes sense.
A final variable can only be assigned once. This assignment does not grant the variable immutable status. If the variable is a field of a class, it must be assigned in the constructor of its class.
Finally Making Sense
To make sense of this, let’s try another example. Let’s pretend we have the following code.
final String str = "hello world"; System.out.println(str.substring(6));
What happens? Did you just say world is printed out? That’s right. However, that is only half the answer. Think about the final String str. Did you catch it yet? A new String object is returned! The original object, the original String is untouched. Strings are immutable as mentioned in the definition above. The final keyword doesn’t affect this property but instead does not let assignments to happen upon the same variable name.
So, to answer my class’ question, “If you make an ArrayList final, can you still add things to it?” Yes you can.
Fixed sample code.
I think you might have missed a the ‘final’ keyword in your first code snippet…
Yeah, I totally missed it. Amazing how silly things like that happen. Thanks for pointing it out!