I have this weird bug that I cannot fix. Can anyone help me? Thank you.
ArrayList<Choices> newSecurityChoicesList =
securityChoicesController.getChoicesList();
System.out.println("first-" + newSecurityChoicesList.size());
securityQuestion.getChoices().clear();
System.out.println("second-" + newSecurityChoicesList.size());
Some explanation:
I created this newSecurityChoicesList ArrayList. It is a local variable in a method.
The first system print out gives me a result of 2.
Why does the second print out give me a result of 0?
Of course it is because of the securityQuestion.getChoices().clear(); method.
But why can a method change a local variable in a method? This method is only called once at the very end of the application.
Thanks in advance.
You are dealing with a reference variable and changing the property of the object it refers to. So while the method’s local variable will be local, it will be referring to the object that was passed in to the method. Again, this is not a bug in Java, but a problem with your understanding about reference variables.
If you don’t want to change the state of the ArrayList passed into the method, then make a deep copy of it in the method before working with it. In other words, you’ll want to create a new ArrayList and then iterate through the parameter ArrayList, making copies of each item in the original list before adding it to the new list.