Adding Values to an ArrayList Object
Populating an Arraylist using Arrays.asList()
The Arrays method asList returns a List of the specified values.
The parameter of asList can come in the form of an array or as a comma separated list of objects. In this tutorial, we will use a comma separated list of objects.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Modify the values in the comma separated list and re-run the code. Note the change in what is stored in the
ArrayList
boolean add (E e)
Appends the specified element to the end of the list. E is the type of the elements in the ArrayList.
The method returns true if the element has been added to the list.
Often the return value is not captured when using ArrayList.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Add a few more classmates to
studentList. Predict the output of the code and run it to determine if your prediction is correct.
void add (int index, E e)
Inserts the specified element at index. All current elements are shifted to the right. E is the type of the elements in the ArrayList.
The method does not return a value.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Add "Susie" at index 1. Predict the output of the code and run it to determine if your prediction is correct.
int size ()
The method returns the number of elements in the ArrayList.
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Add more student names to
studentList. Predict the output of the code and run it to determine if your prediciton is correct.
Complete List of ArrayList Tutorials
Resources