Objective: Use the ArrayList class
Run the following example in BlueJ, make sure you understand how it works!
public class Student { private String name; private int number; public Student(String newName, int num) { name = newName; number = num; } public String getName() { return name; } public String toString() { return name + " " + number; } }
import java.util.*;
import java.util.*;
public class ArrayListStudent {
/**
* prints contents of arrayList
*/
public static void printList(ArrayList< Student > x) {
System.out.println("");
/** rewrite using the for-each loop **/
for (int i = 0; i < x.size(); i++)
System.out.print(x.get(i) + ", ");
System.out.println();
// old version of java
// System.out.println((Student)x.get(i));
}
/**
* creates arrayList of students
*/
public static void main(String args[]) {
ArrayList< Student > list1 = new ArrayList< Student >();
// Old version of java
// ArrayList list1 = new ArrayList();
Student s1 = new Student("Pat",123);
list1.add(s1);
list1.add(new Student("Sue",456));
list1.add(new Student("Candy",789));
printList(list1);
list1.add(2, new Student("Ann",121));
printList(list1);
System.out.println(list1.get(1));
printList(list1);
System.out.println(list1.remove(1));
printList(list1);
System.out.println(list1.set(2,new Student("Alex",246)));
printList(list1);
}
}