I want to make turn this program's array into an ArrayList. So far I know that the array will turn into
ArrayList<StudentList> list = new ArrayList<StudentList>();
and that each list[i] will turn into:
list.get(i)
however I am not sure what the following line will be in order to satisfy the ArrayList version
list[i] = new StudentList();
so here is the full code:
public static void main(String[] args) {
StudentList[] list = new StudentList[5];
int i;
for (i = 0; i < list.length; ++i) {
list[i] = new StudentList();
System.out.println("\nEnter information of Student _" + (i + 1) + "\n");
list[i].DataUserPrompt();
}
for (i = 0; i < list.length; ++i) {
list[i].DisplayStudentData();
}
File file12 = new File("s_records.txt");
try {
PrintWriter output = new PrintWriter(file12);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
new StudentList[5]
is an array of size 5, with all valuesnull
, so you create 5 objects usingnew StudentList()
and assign to the 5 array indexes.However,
new ArrayList()
creates an empty list (size 0). Note thatnew ArrayList(5)
also creates an empty list, it is just optimized to store 5 elements. So you need to create and add 5 objects:The above is equivalent to the array code:
In both cases you end up with a
list
of size 5, with 5 objects.Yes, this is correct, but normally you will see
List
instead ofArrayList
.The reason for this, is the concept of Program to an Interface. Imagine you want to switch from an
ArrayList
to an other data-type of typeList
.. You easily do it without to worry, if your code is now broken.Since
list
is now an object, you must interact with it through methods. On oracle's documentation forList
andArrayList
you will find many of them.But for this scenario you will need
add(E e)
. You can look upE
in the documentation too and it means:With other words:
E
will be yourStudentList
.You can use the add(int index, E element) to insert an element at the specified position.
So
list[i] = new StudentList();
will becomelist.add(i, new StudentList());
.But in your case the list is not already populated, so you should use add(E element) otherwise you'll get
IndexOutOfBoundsException
because the index will be bigger than the current size of the list: