80 likes | 190 Views
In Java, handling dynamic arrays can be easily done using the ArrayList class found in the java.util package. Unlike traditional arrays, ArrayLists can grow and shrink as needed. They hold elements of type Object, requiring casting when retrieving items. The ArrayList automatically reallocates a larger array when the current one is full, ensuring efficient memory use. With methods like add and size, managing collections of objects becomes straightforward. This flexibility is particularly useful when the number of items is unknown ahead of time.
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 !!!