ArrayList Type
Previously, you saw that an ArrayList could be created with a simple line of code:
ArrayList someList = new ArrayList();
This works to create an ArrayList, but there's one issue: it doesn't state what Class of Objects it will hold. In most cases you'll want an ArrayList that only holds Objects of one Class, so your program will know what it's getting when it accesses an element in it. To specify the Objects that an ArrayList will hold, you use the Angle Brackets syntax. For example: *
ArrayList<String> someList = new ArrayList<String>();
This code will create an ArrayList of String, which will only hold String Objects.
You can create an ArrayList that holds any class of Objects. For example, the following line of code will create an ArrayList of Vehicles:
ArrayList<Vehicle> garage = new ArrayList<Vehicle>();
ArrayList is known as a generic class, and it uses angled brackets to specify what Class of Objects it deals with. An ArrayList of one type cannot be re-assigned later to an ArrayList of another type. For example, the following code will cause a compile error (when it appears after the above code):
someList = garage;
Since someList
is an ArrayList of String, it cannot be assigned to garage
which is an ArrayList of Vehicle.
Task
Modify the ArrayList notes
in the Notebook class so that it only takes in Note Objects.
* In Java 7, you can leave out the brackets when creating the ArrayList, so the following code will also work: ArrayList<String> someList = new ArrayList<>();
Challenge
In one line of code, create an ArrayList called blobs
for holding Blob Objects.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Shane
Nov 4, 6:44 PMCan't get this to work:
import java.util.ArrayList;
public class Notebook
{
private ArrayList notes;
}
Gives a null pointer exception when I use the addNote method
Shane
Nov 4, 7:52 PMSorted!
Jason Runkle
Apr 15, 11:41 PM"Modify the ArrayList notes in the Notebook class so that it only takes in String Objects."
Is it just me, or do you actually want the ArrayList notes to be taking Note Objects rather than String Objects...?
Learneroo
Apr 17, 5:11 PM@Jason, thanks, corrected.