80 likes | 182 Views
Array Lists. Arrays in Java. Can set size at run time (as in C++) int actualSize = …; Emp [ ] staff = new Emp [actualSize]; Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily. ArrayList class in Java.
E N D
Arrays in Java • Can set size at run time (as in C++) int actualSize = …; Emp [ ] staff = new Emp [actualSize]; • Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily.
ArrayList class in Java • It is a library class defined in java.util package • Array that will shrink and grow dynamically • Lower bound is 0 • Holds elements of type Object so you’ll need to cast whenever you take an item out of an array list
add Method ArrayList staff = new ArrayList( ); staff.add (new Emp ( …) ); staff.add (new Emp (…) ); • ArrayList class manages internal array of Object references. • When it gets full, then the array list automatically creates a bigger array and copies objects in smaller array to bigger array.
size Method • Returns actual number of elements in array list staff.size ( ); • When you know it has reached permanent size staff.trimToSize ( );
Accessing Array List elements • Nothing is free • To set ith element: staff.set (i, harry); • To get ith element (Object), must cast employee e = (Emp) staff.get( i);
ArrayList Trick • Flexible growth and convenient element access • First make an array list and add elements ArrayList list = new ArrayList ( ); while ( …) { x = …; list.add (x); } • Then use toArray method to copy elements into array.
ArrayList Trick • Then use toArray method to copy elements into array. X [ ] a = new X [list.size ( ) ]; list.toArray (a); • I used this in my solution to Program 2 because you don’t know how many items there are until you’ve finished reading them all !!!