Introduction to Java
What is the Collections framework?
In Java, a collection is a group of objects, called elements. And the Java Collections framework is a set of classes and interfaces that helps us manage these groups of elements in our programs. Let's start by learning about the different types of collections in Java. There are 4 main types:
- Lists allow us to store elements in a specific order, and we can access them easily;
- Sets are similar to lists, but it doesn't allow duplicate elements;
- Maps allow us to store elements in a way that we can easily find them later using a key;
- Queues allow us to store elements in a way that we process them one at a time, like a line of people waiting for a ride at an amusement park.
All of these collections are part of the Java Collections framework, and they have their own specific classes that we can use in our programs, like
One of the most commonly used classes in the Java Collection Framework is the ArrayList. In this lesson, I’ll introduce you to the ArrayList class, and how to create an ArrayList, and perform various operations on it.
Creating ArrayList and Add Elements
Let's start by creating an
In the above example, we have created an ArrayList called names and added three elements to it. To display the elements of the ArrayList, we have used the
In addition to adding elements to the ArrayList, we can also perform various other operations on an ArrayList.
Retrieving an element from the ArrayList
To retrieve an element from the
ArrayList, we can use the
get() method. The
get() method takes the index of the element as its argument. For example, to retrieve the second element from the
ArrayList names, we can use the following code:
The output will be: Second element: Jane
Updating an element in the ArrayList
To update an element in the ArrayList, we can use the
set() method. The
set() method takes two arguments, the index of the element to be updated and the new value of the element. For example, to update the second element of the ArrayList names to "Jack", we can use the following code:
Removing an element from the ArrayList
To remove an element from the ArrayList, we can use the
remove() method. The
remove() method takes the index of the element to be removed as its argument. For example, to remove the second element from the ArrayList names, we can use the following code:
These are some of the most commonly used operations that can be performed on an ArrayList.
We use the Collections framework when we work with a list of items.
ArrayList is one of the most widely used classes in the Java Collection Framework. It is a resizable array, which means its size can be changed dynamically as you add or remove elements. This makes it a very convenient data structure to use in various programming scenarios.
What is the default size of an ArrayList in Java?
Select the correct answer
How to add an element to an ArrayList in Java?
Select the correct answer