Skip to main content

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!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.