When you first begin programming in Java and start working with data structures, you will almost certainly come across the phrases array and arrayList. When should an Array
or an Arraylist
be used? What is the difference between constructing an Array
and an ArrayList
? In this post, I'll explain how these two forms of arrays work and let you chose which to use at the end.
What Is An Array?
An array
is a container object that holds a fixed number of single-type values. The length of an array
is determined when it is created. Its length is fixed after it is created. It cannot be changed.
When you have similar data and want to preserve the same values, you may use an Array
. It might be a collection of numbers, names, words, or other data.
Creating an Array
of size.
Assume we have a list of student names, and we want to build an array to keep them. Let us now see how it works in code.
String[] myFriendsNames = new String[10];
You'll notice that we've surrounded the word string in a square bracket <>
. It signifies that we have a string-type Array
. myFriendsNames
is the next item you notice. That is the variable name that takes our friends' names. By initializing the array
, the =
produces an array
of myFriendsNames
objects. Then we give it a 10 size. This indicates that we are stating that the size of myFriendsNames
will not be greater than or less than ten. The Array size is fixed. It can not increase nor decrease.
Iniatializing an Array With Values
String[] myFriendsNames = {"Nehimiah," "Lekan," "James," "Joy," "Mike," "Janet," "Jacob," "Thomson," "Blessing," "Mike"};
Note that we don't have to specify the size. That's because we defined the size with the values we entered. Because the variables are all 10, the size will be 10. As previously stated, array
increases or decreases.
An array
may hold everything from simple data types like int
, double
, short
, long
, and Boolean
to things like books, dogs, cats, and tables.
How To Get A Value From An Array
To retrieve a value from an array
, you must give the index of the desired item.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
This means that the first element has an index of 0, the second has an index of 1, and so on. We shall supply the array variable name and the index if we want to fetch the entries at index [3]
. Let's try something similar.
System.out.println(myFriendsNames[3]);
//Joy
Joy will be written as the value in index 3.
How to Determine the Length of an Array
To get the length of an array, perform the following:
System.out.println(myFriendsNames.length)
//10
This will print 10 as the lenght of our array.
How To Modify An Element of Array At A Certain Index.
Assume we wish to replace Nehimiah at index 0 with Toby. This may be accomplished by completing the following:
myFriendsNames [0] = "Tobi"
//To print it.
System.out.println(friendsArray[0]);
//Tobi
What You Can Not Do With An Array.
An array cannot be expanded since its size is set and cannot be modified.
An array element cannot be removed. Because, once again, the size is fixed.
What is An ArrayList
In Java, an ArrayList is used to store a dynamically sized collection of elements. Unlike fixed-size arrays, an ArrayList grows in size automatically as new elements are added to it.
Creating an Arraylist
To create an Arraylist
, repeat the preceding steps but in a different order.
ArrayList<String> myFriendsList = new ArrayList<>();
As you can see, we have an ArrayList
and a type string
that accepts names in the angle bracket <>
. The ArrayList is then instantiated using =
, angle brackets <>
, and parentheses ()
. You may have noticed that we did not mention the size in the arraylist
. This is due to the fact that ArrayList
does not have a size provided. It can be increased or decreased by adding or removing values. It expands and contracts on its own. This is one of the reasons why programming with ease is useful with ArrayList
.
Initializing an array list with values
ArrayList<String> myFriendsList = new ArrayList<>(Arrays.asList("Nehimiah", "Lekan", "James", "Joy", "Mike","Janet", "Jacob", "Thomson", "Blessing", "Mike"));
The only difference is that we are giving data to the array list, which is indicated by the Arrays.asList
in parenthesis. In the parentheses, we pass comma-separated values. This allows us to add and delete values and work around them.
Use Integer Instead Of Int In An ArrayList.
Although an ArrayList
can only store objects, you can get around this limitation by utilizing wrapper classes for primitive data types.
So, let us suppose we wish to save a student's exam score. We'll have to do something similar down below.
ArrayList<Integer> StudentsScore = new ArrayList<> (Arrays.asList(65, 77, 66, 89, 98,97, 88, 77, 78, 65));
If you need to utilize a primitive data type, use Integer instead of int.
Getting Values From An ArrayList
To get a value from an ArrayList, you must give the index of the desired value.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
This indicates that the first element has an index of 0, the second has an index of 1, and so on. We shall supply the ArrayList variable name and the index if we want to obtain the entries at index [1]. We'll do something similar.
System.out.println(studentsScore.get(1));
//As the value in index 1 will print 77.
//77
How To Determine The Length of An ArrayList
We shall do the following to determine the length of an ArrayList
:
System.out.println(studentsScore.size())
An Array differs from an ArrayList
in that an array employs a field, whereas an arraylist uses a method call. To access the ArrayList
, we utilize the size()
function.
How To Insert An Element At The End of An Arraylist
We'll perform something like this to add an element to an ArrayList
.
studentsScore.add(34);
System.out.println(studentsScore.get(10));
//10
How To Change An ArrayList Element At A Specific Index
One of our students received an incorrect score. The score must be changed to the proper score, which is at index 0. We may do this by doing the following:
studentsScore.set(0, 89);
System.out.println(studentsScore.get(0));
//89
The set() function was used to provide the index to be changed. Index 0 is the index position we wish to modify in this situation, followed by the value we are bringing in.
How to Remove an Arraylist Element
studentsScore.remove(98);
System.out.println(studentsScore.get(4));
//97
//Because 98 is no longer present, we obtained 97 at index 4.
wrapping up
I was able to explain Array and ArrayList through this article. I explain what an array can and cannot handle, as well as the differences between Array and ArrayList. That, I feel, will inform your decision about which to use.
If you want to learn how to loop over an array, please see my earlier post on how to looping through an array and ArrayList.
ArrayList simplifies programming by giving you so many opportunities to do anything you want with an array.
Do you like working with Arraylist? Please notify me in the comments section.
Top comments (0)