How to use an ArrayList

Java ArrayList Class with an implementation that shows an intermediate yet easy to use code

Java ArrayLists

What are they and why do we use them?

An ArrayList is very similar to an array, with one big difference. Your standard Java Array, once created, is a fixed size and does not resize if values are added to it or taken away from it. This is when an ArrayList is useful to use. It can expand to accommodate any amount of values stored inside it.

When it is created, it contains an initial value, as soon as it is exceeded the collection will automatically expand. Not only that but if an element of the collection is removed the array will automatically decrease in size to reduce its load on the program.

An ArrayList can be written in this format:

ArrayList arrLst = new ArrayList();

Then we can start to add elements to the ArrayList:

  arrList.add("a");
  arrList.add("1");
  arrList.add("!");
  arrList.add("@");
  arrList.add("{a}");
  arrList.add("example");
  arrList.add("[email protected]");

An Array accepts any kind of character value and even parameters from other variables:

  // New ArrayList used to store values
  ArrayList arrList = new ArrayList();

  // Make a new string and find its length
  String testString = "Here is a test string";
  int len = testString.length();

  // Add the length to the ArrayList
  arrList.add(len);

  // Print the contents of the aArayList
  System.out.println(arrList);

The program will output the following: [21]

So why do we use it?

As mentioned above, it is extremely flexible allowing for the addition and subtraction of variables.

Another great advantage of the ArrayList Class is that it is Object-Oriented so it can be built upon and be given greater functionality when necessary.

More details on the ArrayList Class can be found here;

Comments

blog comments powered by Disqus