DEV Community

Cover image for ArrayList vs Array In Java
Isah Jacob
Isah Jacob

Posted on

ArrayList vs Array In Java

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 Arrayor 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 Arrayof 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];
Enter fullscreen mode Exit fullscreen mode

You'll notice that we've surrounded the word string in a square bracket <>. It signifies that we have a string-type Array. myFriendsNamesis the next item you notice. That is the variable name that takes our friends' names. By initializing the array, the =produces an arrayof 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"};
Enter fullscreen mode Exit fullscreen mode

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 arraymay hold everything from simple data types like int, double, short, long, and Booleanto 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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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<>(); 
Enter fullscreen mode Exit fullscreen mode

As you can see, we have an ArrayList and a type stringthat 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 ArrayListdoes 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"));
Enter fullscreen mode Exit fullscreen mode

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 ArrayListcan 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));
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

An Array differs from an ArrayListin 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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)