Java我认为我的问题是如何重用一个对象将2条记录添加到我的数据库程序中

问题描述 投票:0回答:1

首先使用有效用户,效果很好第二次尝试使用新名称失败!

// First use of validUser works perfectly
username = "Fred";
password ="Flintstone";
User validUser = new User(username,password);
data.add(validUser);
System.out.println("Successful!");  

// Second attempt with new names fails! 
username = "John";
password = "doe";

User validUser = new User(username,password);
// ERROR: variable validUser is already defined    
// I just want to put two records into the DB.
// Can't I (or how can I)  just reuse validUser?
// I tried to take "new" out but that didn't work either. Thanks!

data.add(validUser);
java object new-operator reusability
1个回答
1
投票

如果要重用相同的变量,只需重新分配引用。validUser = new User(...);

在数据类型之前,就像您要在相同范围内两次声明相同变量->禁止。

通过这种方式避免这种变量的重新分配。它易于出错,并降低了代码的可读性(首选不可变变量)。只是声明新的,或者根本不需要通过在需要的地方内联它们来声明。像这样。data.add(new User());

© www.soinside.com 2019 - 2024. All rights reserved.