Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 anArrayor anArraylist be used? What is the difference between constructing anArray and anArrayList? 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?

Anarray is a container object that holds a fixed number of single-type values. The length of anarray 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 anArray. It might be a collection of numbers, names, words, or other data.

Creating anArrayof 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=newString[10];
Enter fullscreen modeExit fullscreen mode

You'll notice that we've surrounded the word string in a square bracket<>. It signifies that we have a string-typeArray.myFriendsNamesis the next item you notice. That is the variable name that takes our friends' names. By initializing thearray, the=produces anarrayofmyFriendsNames objects. Then we give it a 10 size. This indicates that we are stating that the size ofmyFriendsNames 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 modeExit 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.

Anarraymay hold everything from simple data types likeint,double,short,long, andBooleanto things like books, dogs, cats, and tables.

How To Get A Value From An Array

To retrieve a value from anarray, you must give the index of the desired item.

[0][1][2][3][4][5][6] [7] [8][9]
Enter fullscreen modeExit 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 atindex [3]. Let's try something similar.

System.out.println(myFriendsNames[3]);//Joy
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 anArraylist

To create anArraylist, repeat the preceding steps but in a different order.

ArrayList<String>myFriendsList=newArrayList<>(); 
Enter fullscreen modeExit fullscreen mode

As you can see, we have anArrayList and a typestringthat 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 thearraylist. This is due to the fact thatArrayListdoes 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 withArrayList.

Initializing an array list with values

ArrayList<String>myFriendsList=newArrayList<>(Arrays.asList("Nehimiah","Lekan","James","Joy","Mike","Janet","Jacob","Thomson","Blessing","Mike"));
Enter fullscreen modeExit fullscreen mode

The only difference is that we are giving data to the array list, which is indicated by theArrays.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 anArrayListcan 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=newArrayList<>(Arrays.asList(65,77,66,89,98,97,88,77,78,65));
Enter fullscreen modeExit 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 modeExit 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 modeExit fullscreen mode

How To Determine The Length of AnArrayList

We shall do the following to determine the length of anArrayList:

System.out.println(studentsScore.size())
Enter fullscreen modeExit fullscreen mode

An Array differs from anArrayListin that an array employs a field, whereas an arraylist uses a method call. To access theArrayList, we utilize thesize() function.

How To Insert An Element At The End of AnArraylist

We'll perform something like this to add an element to anArrayList.

studentsScore.add(34);System.out.println(studentsScore.get(10));//10
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 onhow 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer | Technical Writer | Youtuber
  • Location
    Yaba, Lagos Nigeria
  • Pronouns
    He
  • Work
    Teaching Programming
  • Joined

More fromIsah Jacob

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp