-
Notifications
You must be signed in to change notification settings - Fork 2
ArrayList
Hello everyone and welcome to a new article here on JavaChallenges. In this article, we will focus on ArrayList
, a very useful class in most projects. So without any waste of time, let's get right into it.
The ArrayList
class is a nice class that is part of the java.util
package. It is a combination of the arrays and lists, making something often used in code. If you ever used arrays, you will know that it is impossible to change the size of the array because it is defined when you create it. However, lists don't have this problem. You define the list, and then you can use the add()
method to add more values or remove()
to remove. The key difference is that creating a list is made without defining a size.
This is the standard array declaration:
String[] array = new String[size];
But you can define an ArrayList
like this:
ArrayList<String> list = new ArrayList<>();
You can see the clear advantage of the ArrayList
in this comparison.
The ArrayList
provides some pretty neat features:
- It allows duplicate elements.
- The elements maintain their insertion order.
- You can access it at random points by using indexes.
You can find one use-case for this useful class in our first beginner challenge, which can be found here. Other than that, we collected some of the most used examples.
In this example, we will consider T
the type of elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
In this example, we will consider T
the type of elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
list.add(element);
In this example, we will consider T
the type of elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
list.remove(element); // Alternatively, you can use the index of the element.
In this example, we will consider T
the type of elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
for(T element : list)
{
// you can use the element!
}
In this example, we will consider T
the type of elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
list.get(index);
In this example, we will consider T
the type of the elements that will be held by this list. The type can be Boolean
, String
, etc.
ArrayList<T> list = new ArrayList<>();
boolean contains = list.contains(element);
Thank you for reading this article on the ArrayList
class. I hope I helped you with finding out more about this class. I'm David and this is JavaChallenges. Have a nice day and remember: coding is fun and Google is your friend :).