3

I'm learning JAVA and i've come across following methods to use Array in a class. what is the difference between them and which one is convenient to use in future?

ArrayList<Integer> quizGrades = new ArrayList<Integer>();
quizGrades.add(95);
quizGrades.add(87);
quizGrades.add(83);

or

int[] quizGrades = new int[3];
quizGrades[0] = 95;
quizGrades[1] = 87;
quizGrades[2] = 83;
DR Keshav
  • 39
  • 2

4 Answers4

3
ArrayList<Integer> quizGrades = new ArrayList<Integer>();

ArrayList is a data structure in the Collections framework.

You need to use arraylist when you don't know the size of the array beforehand. Array list dynamically resizes the array (insert and delete operations).

On the other hand,

int[] quizGrades = new int[1] 

does not resize the array and you need to provide the size beforehand. Also deleting items becomes cumbersome and it is better to use Arraylist if you are deleting items.

This is the main difference. You can read more about insert, remove time visit, https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aditya K
  • 466
  • 4
  • 8
0

The ArrayList is a class in the Java Collections framework while the int[] is a special array type in Java.

ArrayList is internally backed by an array and allows resizing the length of the array, while the int[] can not be modified in length once it is initialized.

For now I would recommend to you to stick to ArrayList since it is much more handy to use and there is great support in the Collections framework to manipulate your data.

Arrays have the advantage of a smaller memory footprint and being slightly more efficient when directly accessing values in the array. After all, ArrayList using an array internally adds a small overhead. But in 99% of the cases this performance penalty is not the issue in your business application because the bottleneck lies somewhere else (network, database, etc.).

To summarize: As a beginner, you should probably stick to the ArrayList and only use arrays if you want to learn working with them or are constrained to use them.

boskoop
  • 1,157
  • 1
  • 10
  • 17
0

The List class and the primitive array data structure in Java are both mechanisms to store and access a collection of objects. The ArrayList class is a resizable-array implementation of the List interface where internally the ArrayList has an array of objects.

Java APIs often have methods that require either an array of objects or a List so there are mechanisms in Java to convert from a primitive array to a List and vice versa.

Converting primitive Array to a List

Use Arrays.asList() to convert from an array to a List.

Integer[] array = new Integer[] { 95, 87, 83 };
List<Integer> list = Arrays.asList(array);
System.out.println(list); // [95, 87, 83]

Converting List to a primitive Array

If want to convert a List to Array use toArray() method.

Integer[] array2 = list.toArray(new Integer[array.size()]);

Likewise, if want to convert primitive int values to List can simply iterate over the values and add them.

   int[] array3 = new int[] { 95, 87, 83 };
   List<Integer> list3 = new ArrayList<Integer>(array3.length);
   for(int val : array3) {
       list3.add(val);
   }
   System.out.println(list3); // [95, 87, 83]

Similarities and Differences between List and primitive array

Both List and primitive arrays both have the first element with an index of 0 and the nth element has an index of n - 1. Accessing an element with index less than 0 or greater than n-1 results in an exception: IndexOutOfBoundsException in list or ArrayIndexOutOfBoundsException in case of the array.

Get and set elements in primitive array

int grade = array[0];
array[0] = 98;
int len = array.length; // number of elements in array
grade = array[-1]; // throws ArrayIndexOutOfBoundsException

Get and set elements in List

int grade = list.get(0);
list.set(0, 98);
int len = list.size(); // number of elements in list
grade = list.get(-1); // throws IndexOutOfBoundsException

Unless the list is immutable (or read-only) then you can add or remove elements from it. See Collections.unmodifiableList(). To grow/shrink a primitive array, you must create a new array and copy of old elements from the old to new array.

In general, primitive arrays and Lists are semantically equivalent but with different syntax. One form can be converted to the other.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
0

ArrayList contains the array word. It is not coincidence.
ArrayList is in fact a Resizable-array implementation of the List interface.
So under the hood, it uses a array to represent data.

In most of cases, using an ArrayList over an array should be favored because it provides very common methods to manipulate the "set" of elements (add(), addAll(), remove(), set(), etc...) that you have to perform manually with an array.

Besides it frees the developers to worry about the size of the "set" of elements that it manipulates and the processing related to increase/decrease capacity of the "set" of elements when the actual size reaches the initial declared size.

Indeeed, with an array, the size is fixed. So, you have to know and specify it at its declaration as in your example : int[] quizGrades = new int[1];.

Besides if the initial size is not enough to store new elements, you should make a copy of the array data in another larger array. Finally what does for you the ArrayList class when it grows.

So when use an array ?

Generally when you need to perform very fine optimizations.
For application developers, the need is rather rare.

Here some use cases :

  • you want spare the little overhead caused by the ArrayList wrapper (CPU, memory)

  • you want to use primitive because it is enough and you need to spare each potential consumed bytes.
    Primitive values occupy less memory as wrapper values.
    Arrays accept primitive values. List and Collection classes don't.

  • you want to master how store and retrieve data of the "set" of elements. It includes rules about capacity increasing and decreasing.

davidxxx
  • 125,838
  • 23
  • 214
  • 215