小编anu*_*ith的帖子

Java Arraylist更改会影响其他变量

我正在使用java fx,在下面的代码中没什么好看的,并且捕获文本字段的focusedProperty来覆盖下面新输入的值.下面的代码更改了在文本字段中输入的人名,当用户单击取消按钮时,它会将旧名称放回文本字段.但由于某些原因,一个魔法发生了,每当我设置这个人的名字时,它会覆盖cancelPerson变量中的字段.无法弄清楚为什么会这样?在设置新值之前,我从人员列表中获取cancelPerson.那么人员名单中的变化怎么会影响一个自变量.知道为什么会这样吗?谢谢.

 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;
   }
}
Run Code Online (Sandbox Code Playgroud)

java javafx list arraylist immutability

3
推荐指数
2
解决办法
212
查看次数

标签 统计

arraylist ×1

immutability ×1

java ×1

javafx ×1

list ×1