如何在Java中将元素追加到ArrayList的末尾? [英] How to append elements at the end of ArrayList in Java?

查看:0
本文介绍了如何在Java中将元素追加到ArrayList的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,在Java中如何将元素附加到ArrayList的末尾?以下是我到目前为止拥有的代码:

public class Stack {

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

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        ArrayList.add(random);
    }

}

随机StringGenerator是一种生成随机字符串的方法。

我基本上希望始终将随机字符串追加到ArrayList的末尾,非常像堆栈(因此称为"Push")。

非常感谢您抽出时间!

推荐答案

以下是语法,以及您可能会发现有用的一些其他方法:

    //add to the end of the list
    stringList.add(random);

    //add to the beginning of the list
    stringList.add(0,  random);

    //replace the element at index 4 with random
    stringList.set(4, random);

    //remove the element at index 5
    stringList.remove(5);

    //remove all elements from the list
    stringList.clear();

这篇关于如何在Java中将元素追加到ArrayList的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆