简体   繁体   English

坚持如何添加到另一个班级的列表

[英]Stuck on how to add to a list in another class

I have a class, DB, that contains a list:我有一个类 DB,其中包含一个列表:

private List<User> users;

along with an addUser method that allows users to be added to the list以及允许将用户添加到列表的 addUser 方法

public User addUser(String name) {

Another class, User, needs to create an instance of the User class, so I tried using the following code:另一个类 User 需要创建 User 类的实例,所以我尝试使用以下代码:

public User(String name) {
        DB.addUser(name);

But it returns the error that I can't make a static reference to the nonstatic method.但它返回的错误是我无法对非静态方法进行静态引用。 I'm at a loss, because to create an instance of the User class, I have to put it into the list, but since the list is private, I have to use DB's methods, but I can't do that without getting an error... Is there any way to fix this?我不知所措,因为要创建 User 类的实例,我必须将其放入列表中,但是由于列表是私有的,我必须使用 DB 的方法,但是如果没有得到错误...有什么办法可以解决这个问题吗?

This function here is calling addUser in a static way.这里的这个函数是以静态方式调用addUser

public User(String name) {
    DB.addUser(name);
}

But this function below requires an object to be instantiated in order to call it (non-static)但是下面的这个函数需要实例化一个对象才能调用它(非静态)

public User addUser(String name) { ... }

So change it to be所以改成

public static User addUser(String name) { ... }

or create an instance of DB and call the method或创建一个 DB 实例并调用该方法

public User(String name) {
    DB db = new DB();
    db.addUser(name);
}

Seems there are some basics which are not clear to you.似乎有些基础知识您不清楚。

  1. Members are always private and to interact them you should create public setter and getter.成员始终是私有的,要与它们交互,您应该创建公共的 setter 和 getter。

    public List getUsers(){ return users;公共列表 getUsers(){ 返回用户; } }

    public void getUsers(List users){ this.users=users; public void getUsers(List users){ this.users=users; } }

  2. As a good coding standard, the naming should describe the behavior which provides specific action Hence作为一个好的编码标准,命名应该描述提供特定动作的行为因此

User addUser(String name)用户添加用户(字符串名称)

seems very ambiguous considering it's actual implementation as given adds User to the list.考虑到它的实际实现,因为给定将 User 添加到列表中,这似乎非常模棱两可。

  1. If DB class is a dependency then it should be instantiated Let's assume you are calling this code from main如果 DB 类是一个依赖项,那么它应该被实例化让我们假设您从 main 调用此代码

    User user= new User();用户用户=新用户(); DB dbInstance=new DB(); DB dbInstance=new DB(); dbInstance.setUsers(new ArrayList()); dbInstance.setUsers(new ArrayList()); dbInstance.getUsers().add(user); dbInstance.getUsers().add(user);

To provide a more specific answer awaiting further requested details提供更具体的答案,等待进一步要求的详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM