ArrayLists

Introduction: Welcome! This tutorial will teach you about how to create and use ArrayLists. What are ArrayLists? ArrayLists, normally referred to as just Arrays, is a type which can contain multiple items. For example; a shopping list could be referred to as an array or shopping items. ArrayLists must be made up of one type only. You are unable to mix and match different types within one ArrayList such as String and Integer. You are able to use custom created classes (using OOP) in ArrayLists. How do I use ArrayLists? ArrayLists are just like any other type of variable expect it is more common to use pre-made methods with ArrayLists compared to other variable types such as Integers. ArrayLists have a few essential functions which are used below such as; .add, .clear and .get. Example: Here is an example of creating a new ArrayList (of the String type), adding some items, outputting the total amount of items in list, outputting each item in the list, then clearing and re-outputting the total amount of items in the list.
  1. ArrayList<String> list = new ArrayList<String>();
  2. list.add("Hi");
  3. list.add("Hey");
  4. list.add("Hello");
  5. System.out.println("Total Items in List: " + list.size());
  6. for (int i=0;i<list.size();i++){
  7. System.out.println("Item in List " + i + " is " + list.get(i));
  8. }
  9. list.clear();
  10. System.out.println("Total Items in List: " + list.size());
Which gives the output:
Total Items in List: 3
Item in List 0 is Hi
Item in List 1 is Hey
Item in List 2 is Hello
Total Items in List: 0
Finished!

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
1 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.