I am wondering, how do I append an element to the end of an ArrayList in Java? Here is the code I have so far:
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 which generates a random String.
I basically want to always append the random string at the end of the ArrayList, much like a stack (Hence the name "push").
Thank you so much for your time!
ArrayList implements the List<E> Interface. To add an element to the end of an ArrayList use: boolean add( E elt ) ; // Add a reference to an object elt to the end of the ArrayList, // increasing size by one.
There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.
To add an object to the ArrayList, we call the add() method on the ArrayList, passing a pointer to the object we want to store. This code adds pointers to three String objects to the ArrayList... list. add( "Easy" ); // Add three strings to the ArrayList list.
The append() method adds a single element towards the end of a list.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With