containing ArrayLists - Integer can be added to b . An...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Constraining the elements of an ArrayList You now know that you can create an instance of class java.util.ArrayList and save it using an assignment like ArrayList b= new ArrayList(); The elements of this list have the apparent class Object . When an element is added to the list, it is automatic- ally promoted to Object . Beginning in Java 1.5, you can constrain the objects of a list by placing a class name, in angular brackets (the less-than and greater-than symbols) after the class name ArrayList . b= new ArrayList<Integer>(); Now, only objects of class
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Integer can be added to b . An attempt to add an object of a class that is not In-teger or a subclass of Integer will be flagged as illegal, and the program wont compile. You can put any class in place of Integer . The ability to constrain ArrayList s in this fashion simplifies some coding and provides more type safety. By using a constrained ArrayList , you can reduce the chance of making an error by adding something to an ArrayList that does not belong there. Constrain you ArrayList s where possible....
View Full Document

This note was uploaded on 07/07/2008 for the course CS 101 taught by Professor Gries during the Spring '08 term at Cornell University (Engineering School).

Ask a homework question - tutors are online