error: cannot assign a value to final variable
count++;
will throw an error. Per Oracle,
A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
You can follow along with that article here. Looking at your code, it seems that you really don't want count
to be final. You want to be able to change its value throughout the program. The fix would be to remove the final
modifier.
When you declare a variable final
you basically tell the compiler that this variable is constant and will NOT change. You declared count
final, but you hadn't initialized (set a value) it yet. That's why you were allowed to set it's value in your constructor public List() {}
: final variables can be initialized once, and after that, they can't be modified.
There are exceptions to this though, if you'd for example created an object with an int value of count, and added a setter, you'd still be able to modify the final object.
Example of that:
public class ExampleObject {
private int count;
public ExampleObject(int count) {
this.count = count;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
}
public class ExampleDemo {
private static final ExampleObject obj = new ExampleObject(25);
public static void main(String[] args) {
obj = new ExampleObject(100); //not allowed: cannot assign a value to final variable
obj.setCount(100); //allowed
}
}
It is throwing error because you have declared count as a final variable. Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.