Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)
recategorized by

How do I append an element to the end of an ArrayList in Java? Here is my code:

public class Stack {

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

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){

        String random = rsg.randomStringGenerator();

        ArrayList.add(random);

    }

}

“randomStringGenerator” is a method that generates a random string at the end of the ArrayList, much like a stack.

1 Answer

0 votes
by (13.1k points)

Here is the syntax, along with some other methods you might find useful:

   //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();

Want to learn java? Check out the core Java certification from Intellipaat. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...