Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arraylist change affect other variables

I am using java fx, nothing fancy in the code below, and catching the text field's focusedProperty to overwrite the newly entered value below. The code below changes a person's name that is entered in the textfield and when user clicks on cancel button it will put the old name back into the textfield. But for some reason a magic happens and whenever I set the person's name it overwrites the field in the cancelPerson variable. Could not figure out why this would happen? I get the cancelPerson from persons list before I set the new value. So how come changes in the persons list can affect an independent variable. Any idea why this would occur? Thanks.

 private ObservableList<Person> persons;
 private Person person;
 private Person cancelPerson;

    personName.focusedProperty().addListener((observable, oldValue, newValue) -> {
                if (!newValue) {
                    final int index = personIdCombo.getSelectionModel().getSelectedIndex();
                    cancelPerson = persons.get(index);
                    final Person person = persons.get(index);
                    person.setName(personName.getText());
                    persons.set(index, person);
                }
            }
    );


class Person{
   private final StringProperty name;
   public Person() {

        this.name = new SimpleStringProperty("testName");           

   }

   public SystemParams(Person person) {

      this.name = person.name;
   }
}
like image 855
anupampunith Avatar asked Jul 13 '26 23:07

anupampunith


1 Answers

Jim Garrison's answer (suggesting the copy constructor) is correct; I just wanted to add another answer to give a helpful way of thinking about references in Java.

I found it helpful to think of an = assignment as a REFERS TO assignment. So, cancelPersons = persons.get(index); is basically saying:

cancelPerson REFERS TO persons.get(index);

Now, where your second line says final Person person = persons.get(index);, think of it as

final Person person REFERS TO persons.get(index);

See how they both REFER TO the same persons.get(index)? Now, whether you use cancelPerson or just person, Java is pointing back to the same overall object, not different ones.

Unless you have a new keyword somewhere, you are not actually creating a new object.

like image 59
Zephyr Avatar answered Jul 16 '26 13:07

Zephyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!