Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append elements at the end of ArrayList in Java?

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!

like image 295
Nora Avatar asked Mar 24 '14 13:03

Nora


People also ask

How do I add elements to the end of an ArrayList?

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.

How do I add items to the end of a List in Java?

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.

How do you append to an ArrayList in Java?

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.

Which method is used to add element at the end of List?

The append() method adds a single element towards the end of a list.


1 Answers

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(); 
like image 168
Edwin Torres Avatar answered Sep 17 '22 04:09

Edwin Torres