Java Reference
In-Depth Information
7.6 Summary
The chapter covered ArrayList class and enum keyword topics, among others. An
ArrayList is an alternative for an array when the size of the array is unknown. The size of
an ArrayList is automatically expended when required. Similar to arrays, a for-each for
loop can be used to iterate over the elements of an ArrayList when the ArrayList does
not need to be modified.
The enum construct is similar to creating a new class. However, instead of merging several
types into a new type, enum enumerates the valid values of an existing type. Each value can
be associated with a string description.
The chapter also presented a multi-class solution of the Coin game. Every class contained
only the methods that were needed to modify the data. Methods that should not be called
outside the class were defined as private . As expected, the tasks of printing to the screen
and reading from the console were not part of the methods in the classes Coin and Change ,
and were left to be implemented in the class that contained the main method.
7.7 Syntax
￿ ArrayList<Employee> a = new ArrayList<>();
Creates a new ArrayList of
￿ ArrayList<Integer> a = new ArrayList<>();
Creates a new ArrayList of in-
Returns the size of the ArrayList .
Inserts the number 3 at the end of the ArrayList a .
a.add(3,new Employee());
Inserts a new employee at position 3. Employees must
exist at positions 0, 1, and 2. The employees at position 3 and after are shifted to the
right by one position.
a.set(2,new Employee("John"));
Changes the element at position 2. An element
at position 2 must exist.
Converts an
￿ Employee[] emps = (Employee[]) empArrayList.toArray();
ArrayList of employees into an array of employees.
￿ a.get(3)
Returns the element at position 3.
￿ a.remove(e);
Removes the first occurrence of the e object from the ArrayList .
￿ a.remove(new Integer(6));
Removes the integer 6 from the ArrayList of inte-
￿ a.remove(3);
Removes the element at position 3 from the ArrayList .
￿ s.charAt()
Returns the character at position 3 (counting starts at 0) for objects
of type String and StringBuffer .
Search WWH ::

Custom Search