通过在Java中传递参数来更新ArrayList

时间:2016-11-21 20:47:05

标签: java arraylist

我正在尝试通过传递参数来创建和更新ArrayList,这样我最终会得到一个说出10个名字的列表;然而,目前的功能似乎并没有起作用 - 任何想法都可以吗?

   public String addClient(String name) {
     ArrayList<String> myList = new ArrayList<String>();
     myList.add(name);

     return myList;
   }

3 个答案:

答案 0 :(得分:3)

每次调用时都会创建一个new ArrayList。这意味着每次调用此方法时,您都会创建一个全新的Collection,并且只将一个客户端存储在其中。您需要保留一个集合的引用并继续添加。您可以通过传入要将其添加到的数组来执行此操作:

public List<String> addClient(String name, List<String> array) {
    array.add(name);
    return array;
}

这似乎不是一个有用的功能,所以我猜这是在一个类中。所以这可能是你想要的方法:

/**
 * Class is not Thread Safe
 */
public class ClientList {
    private final ArrayList<string> clients;

    public ClientList() {
        this.clients = new ArrayList<>();
    }

    public void addClient(String client) {
        this.clients.add(client);
    }

    public List<String> getClients() {
        // Note: Never give a reference to the internal objects of the class
        // as that means someone outside this class can own a reference to it
        // and can update the object without you knowing (by not going
        // through this class)
        Collections.unmodifiableList(this.clients);
    }
}

答案 1 :(得分:0)

这是你需要做的:

ArrayList<String> myList = new ArrayList<String>();

public void addClient(String name) {
    myList.add(name);
}

如果在方法内部创建一个列表,它将只有一个值,并且一旦方法执行完成就会消失(除非它被返回)。看看不同的范围here。您应该在类级别创建一个列表并将元素添加到其中。

此外,方法不需要返回任何内容,因此最好将类型更改为void

答案 2 :(得分:0)

您的方法存在的问题是,每次调用方法addClient时,都会创建一个新的ArrayList。 我认为这对你有用:

static ArrayList<String> myList;

public static void main(String[] args) {
    myList = new ArrayList<>();
}

public void addClient(String name){
    myList.add(name);             
}