简体   繁体   English

如何在实例化类数组列表中添加元素

[英]How to add an element in an instanced class arraylist

I have this code to create a class User我有这个代码来创建一个类用户

public class User {

    private String name;
    private ArrayList<User> owners = new ArrayList<>();


    public User(String name, ArrayList<User> owners) {
        this.name = name;
        this.owners = owners;

    }


    public String getName() {
        return name;
    }

    public void addOwner(User owner) {
        owners.add(owner);

    }

If i create an instance of this class with如果我创建这个类的一个实例

User jhil = new User(name, new ArrayList<>());

What do i do to add a string element to the arraylist我该怎么做才能将字符串元素添加到数组列表中

I've tried with the addOwner method with我试过用 addOwner 方法

jhil.addOwner(jhilsara);

but i get a the method addOwner(String) is undefined for the type User error但我得到一个方法 addOwner(String) 未定义为类型 User 错误

I've also tried with the ArrayList add method我也尝试过使用 ArrayList 添加方法

jhil.add(jhilsara);

But that doesn't work either.但这也行不通。

So my question is what do i need to do in order to add something to the arraylist of an instanced of my class User所以我的问题是我需要做什么才能将某些内容添加到我的类 User 的实例的数组列表中

You have your ArrayList set to contain objects of the User class, not Strings.您将 ArrayList 设置为包含 User 类的对象,而不是 Strings。 Change the declaration of it to:将其声明更改为:

private ArrayList<String> owners = new ArrayList<>();

Then, you also have to change addOwner to:然后,您还必须将 addOwner 更改为:

public void addOwner(String owner) {
    owners.add(owner);
}

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

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