ArrayLists

Submitted by: 
Language: 

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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.