ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
31. null as an Element
Answer:
The equals(Object)
method could be made case insensitive.
Another good modification of the program would be to allow the user to put new entries into the list.
null
as an Element
null
as an Element
ArrayList
element can be an object reference or the value null
. When a cell contains null
, the cell is not considered to be empty. The picture shows empty cells with an "X" and cells that contain a null with null
.
import java.util.* ; public class ArrayListEgFive { public static void main ( String[] args) { // Create an ArrayList that holds references to String ArrayList<String> names = new ArrayList<String>(); // Add three Object references and two nulls names.add("Amy"); names.add(null); names.add("Bob"); names.add(null); names.add("Cindy"); System.out.println("size: " + names.size() ); // Access and print out the Objects for ( int j=0; j<names.size(); j++ ) System.out.println("element " + j + ": " + names.get(j) ); } } |
The program prints out:
size: 5
element 0: Amy
element 1: null
element 2: Bob
element 3: null
element 4: Cindy
The cells that contain null
are not empty, and contribute to the size of the list. It is confusing when null
s are elements of some cells. Don't write your programs to do this unless there is a good reason. A good reason might be that you don't want elements to move to new cells when other elements are deleted. So rather than use remove()
you assign null
to a cell.
Question 30:
If you wish to remove Cindy from the
ArrayList
, should you set that cell tonull
?names.set( 4, null )