How to Use a Java ArrayList | TechBuzz

- Advertisement -


​​​​​​A Java ArrayList is a general-purpose resizeable array. It provides several useful features that operate on the data it contains. You can access elements using an index, perform CRUD operations, resize the array, and iterate over its elements.

To use an ArrayList in your program, you will first need to import the java.util.ArrayList package. This will provide access to the three ArrayList constructors, along with several methods. Some of the more popular ArrayList methods include add(), addAll(), set(), get(), indexOf(), and remove().

Subclasses of the AbstractList

The AbstractList class implements the List interface and gives you access to data structures such as an ArrayList. Other direct and indirect subclasses of the AbstractList include:

  • The LinkedList data structure supports fast insertion and removal at intermediate indices.
  • The Vector data structure is like an ArrayList, but synchronized. It’s suitable to use in place of an ArrayList for multithreaded applications.
  • The Stack data structure supports operations for mimicking a last-in-first-out list. Naturally, it synchronizes because it extends the Vector class.

These special classes are outside the scope of this article. However, you will learn how to set up and use a general-purpose Java ArrayList.

MAKEUSEOF VIDEO OF THE DAY

Creating an ArrayList

Creating an ArrayList in Java is simple. You can create an empty ArrayList using the no-arguments constructor.

- Advertisement -

The following code creates an empty ArrayList for holding strings.

ArrayList<String> alist = new ArrayList<String>();

If you know how many items your array list will contain, you can specify the initial capacity. This initial capacity is just a hint for memory allocation. Whether you specify a capacity or not, the ArrayList has no memory restrictions. If you know and specify the initial capacity, you might get a slight performance improvement.

- Advertisement -
ArrayList<String> alist = new ArrayList<String>(8);


The code above creates an ArrayList (alist) that allocates eight index positions in memory.

Populating an ArrayList

Adding Items at the End

Populating an ArrayList is quite easy. Just use the add() method to add a single item to the end of the ArrayList. Here is an example:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("cantaloupe");
alist.add("orange");
System.out.println(alist);

The code above displays the following output in the console:

[apple, banana, cantaloupe, orange]

The size() method returns the number of items in an ArrayList.

System.out.println("Number of elements in the arraylist: " + alist.size());

Adding Items at a Specified Index

Want to add an item at a specific index position? Simply provide the add() method with the index position you want to use, followed by the item you want to add:

alist.add(3, "grapes");
System.out.println(alist);

The code above displays the following output in the console:

[apple, banana, cantaloupe, grapes, orange]

In the ArrayList above you will notice that “grapes” is fourth in the list. This is at index position three since a Java ArrayList begins at index position zero.

Adding a Bunch of Items

You can add items from any collection in the Java Collections hierarchy too. An ArrayList is a specific type called List. Here is a way to construct a List from a bunch of items (using Arrays.asList()) and add it to an ArrayList.

List<String> items = Arrays.asList("pear", "cherry");
alist.addAll(items);
System.out.println(alist);

You can also provide an index as the first argument of the addAll() method. This will allow you to place the items List at any position in the ArrayList.

Accessing Items

After you add the items to an ArrayList, how do you access them again?

Accessing Items With an Index

If you know the item’s index, you can use the get() method to retrieve the element at specific index position.

String item = alist.get(2);
System.out.println("Item at index 2 is: " + item);

Finding Items

What if you don’t know the index of the item? You can use indexOf() to check if the item is present in the array and retrieve the item using the returned index.

System.out.println(alist);
int index = alist.indexOf("orange");
if (index < 0)
System.out.println("Item \"orange\" not found");
else
System.out.println("Item \"orange\" found at index " + index);


The indexOf() method returns -1 when the program does not find an item:

index = alist.indexOf("grape");if (index < 0) 
System.out.println("Item \"grape\" not found");
else
System.out.println("Item \"grape\" found at index " + index);

Iterating Over an ArrayList

The most common use of an ArrayList is iterating over the elements. You can accomplish this in several ways. The following code contains a for loop that iterates over an ArrayList and prints each item in the console:

for (String fruit : alist) 
System.out.println("Found fruit \"" + fruit + "\"");


Before Java’s enhanced for loop developers would iterate over the items in an ArrayList with an iterator. An iterator can also remove elements during the process of iteration, as the example below illustrates. Note that the code below makes a copy of the ArrayList and works on the copy.

ArrayList<String> blist = new ArrayList<String>(alist);for (Iterator<String> iter = blist.iterator() ; iter.hasNext() ; ) 
String fruit = iter.next(); if (fruit.startsWith("c"))
iter.remove();
else
System.out.println("Keeping \"" + fruit + "\"");

Replacing Items

The set() method allows you to replace an existing item in an ArrayList. This method takes two arguments; the index position of the item you want to replace and the new item.

alist.set(5, "pineapple");
System.out.println(alist);

Removing Items

If you know the index position of an item that you want to remove from a list, you can use the remove() method to achieve this. The remove() method takes an index position or an item as an argument.

String fruit = alist.remove(2);
System.out.println("Removed element at 2: " + fruit);

The code below returns true if the program locates and removes the specified item.

fruit = "grapes";
System.out.println("Remove " +fruit+ " from the list? " + alist.remove(fruit));


The Value of Choosing the Right Data Structure

Knowing how to create and manipulate ArrayLists in Java is an invaluable skill. An ArrayList is one of several data structures that you can use to store data. So, it might not always be the best-suited data structure for what you want to accomplish.

For example, if you want to store your data with a unique key and the storage order is not important, then a HashMap is a better option than an ArrayList. It is, therefore, an asset to know how to use a wide variety of data structures.


Data structures in programming
6 Data Structures Every Programmer Should Know

Read Next


About The Author



Source link

- Advertisement -
Adminhttp://techbuzz.asia
I am admin of techbuzz.asia blog & I provide tech-related news. As a part of my hobby, I make content related to technology and gadgets reviews too. I love to be a content creator apart from it, I am a full-time employee in an MNC company and manage blogs systematically. You can mail me at [email protected]

More from author

Related posts

Advertisment

Latest posts

Windows 11 version 22H2 – a new major update coming to us in the second half of the year | TechBuzz

Microsoft is currently working intensively on a new version of Windows known as 22H2 version and codenamed Sun Valley 2. This is the...

Honor Magic 4 Pro: Chinese manufacturer listens to critics | TechBuzz

Honor wants to take Huawei's place and has already done so in China. Now, with the Honor Magic 4 Pro, another top smartphone...

Want to stay up to date with the latest news?

We would love to hear from you! Please fill in your details and we will stay in touch. It's that simple!