Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which array type should be used in JAVA and why? [duplicate]

Tags:

java

arrays

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;
like image 265
DR Keshav Avatar asked Jul 21 '26 02:07

DR Keshav


1 Answers

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

like image 158
Aditya K Avatar answered Jul 23 '26 17:07

Aditya K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!