【问题标题】:How can I code correctly to keep unique attributes in separate objects如何正确编码以将唯一属性保留在单独的对象中
【发布时间】:2017-06-05 06:58:25
【问题描述】:

我在user.java中有以下结构

public class User(){

    string fname;
    string lname;
    string email;

    public User(){
        this.fname = randomCharGenMethod();
        this.lname = randomCharGenMethod();
        this.email = randomCharGenMethod();
   }
}

在另一个 java 类中,我创建了以下对象。

static User user1 = new User();
static User user2 = new User();

当我继续创建对象时,它们都有相同的 fnamelnameemail

实际上,我希望它们具有唯一的 fnamelnameemail,因为它们是通过字符串生成方法生成的

【问题讨论】:

  • 我想我们也需要看看randomCharGenMethod源代码
  • 效果很好 public static String randomCharGenMethod() { return RandomStringUtils.randomAlphabetic(5); }
  • 如果您使用的是string,如何编译?是自定义类型吗?
  • 我用了 String 抱歉打错了
  • 我不能确定,因为你没有分享randomCharGenMethod(),但我猜这是你的问题stackoverflow.com/questions/5533191/…

标签: java object attributes unique


【解决方案1】:

User1、User2 被声明为静态是否有任何具体原因?当你处理静态变量时,你应该记住它们是在实例之前加载的。

考虑这个代码,作为一个更简单的例子:

public class User() {
static string fname;
static string lname;
static string email;

public User() {
    this.fname = randomCharGenMethod();
    this.lname = randomCharGenMethod();
    this.email = randomCharGenMethod();
 }
} 

User 的任何新实例都将共享相同的 fname、lname 和 email 值,因为它们是在任何实例化之前加载的。

考虑到这一点,也许如果 user1、user2 不是静态的,它们可以保存单独生成的值。

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 2014-04-11
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多